Token LabSearch

MCP / AGENT INFRASTRUCTURE

Model Context Protocol (MCP): tools, transport, and authorization

Follow an SRE incident from tool discovery to a defensible diagnosis. Compare MCP versions, authorization and retries, then run a local Python example.

Sources & version details
In this article

Why MCP exists

You should be comfortable reading a JSON request, an HTTP status, and a small Python function. By the end, you can trace a call, choose the right primitive and transport, and explain what happens when access is denied or a write times out.

At 16:07 UTC, an on-call engineer sees checkout errors rise and asks whether the 16:00 release is responsible. A useful assistant needs the 5xx rate by version and time window, the deployment record, and the runbook’s escalation criteria. The records live in separate systems, and the engineer may work in an IDE, an incident console, or a chat app.

The Model Context Protocol (MCP) is an open application-level protocol that lets AI applications discover and use external capabilities. It defines how to describe tools, read resources, obtain prompt templates, and return results and errors. A monitoring team can expose a common interface that several hosts consume. Each host still decides what to present to the model and how to use the response. The monitoring API, business rules, and incident owner remain in place.

If four hosts integrate six systems individually, there can be up to 24 host–system adapters. With one shared protocol, the first-order integration count is closer to four client integrations plus six server integrations. That is a topology illustration, with identity, feature support, testing and policy work still needed for every real deployment. For one application with one stable internal API and a deterministic call path, use the simpler integration. MCP helps most when capabilities are reused across hosts, built by independent teams, or discovered dynamically.

Who decides and who executes

The host is the incident application. It owns the conversation, the user's identity and approval UI, the set of tools offered to the model, and the turn or step budget. Inside it, the MCP client speaks JSON-RPC to a particular server. The model can propose a tool plus arguments. The host can decline, show an approval request, or dispatch the permitted call.

The MCP server is a service boundary. It advertises capabilities, validates each request, enforces policy and calls the monitoring API with a separately scoped identity. The monitoring backend owns metric storage and query semantics. A second MCP server can provide release records without receiving the conversation or the first server’s credentials. The host composes their outputs and supplies a minimal evidence bundle to the model.

MCP request and evidence flow. The host dispatches the action, and the server authorizes access before querying the metrics backend.
MCP request and evidence flow. The host dispatches the action, and the server authorizes access before querying the metrics backend.
View full-size diagram

Tools, resources, and prompts

Primitive Discover and invoke Use it in this incident
Tool tools/list, tools/call Query 5xx counts by service and time window. Other tools can change business state.
Resource resources/list, resources/templates/list, resources/read Read the known URI runbook://checkout/5xx; a resource template can represent runbooks for more services.
Prompt prompts/list, prompts/get Render a reusable incident-summary message with slots for observations, competing hypotheses, and the next check.

Read a resource when you already know what you want, such as a particular document or record. Use a tool for search, computation or an explicit action. A prompt supplies messages to the application and can be user-selectable. The model may suggest tool calls, while the host controls exposure and execution. A capability declaration describes what the server implements. It grants no caller permission.

A narrow tool contract helps the model choose correctly and helps servers enforce constraints. For get_error_rate, the input schema can name a service and define permitted window lengths. The output should make request counts, error counts, timestamps, and environment explicit. Schema validation checks the representation. Server policy then checks whether the authenticated subject may read that resource.

Versions, transports, and discovery

Question Handshake revisions through 2025-11-25 2026-07-28
What starts the exchange? initialize negotiates capabilities and a version, then the client sends notifications/initialized. Requests declare the version and client capabilities in params._meta. A client may call server/discover first.
Where is state kept? HTTP implementations can use a protocol session with a session ID. The protocol has no session identity. Applications can persist named records and pass identifiers in tool arguments.
How does a tool ask for more input? Optional features can send a separate server-to-client request during an operation. Multi Round-Trip Requests (MRTR) can return input_required. The client sends a new invocation with the collected responses and any server-provided request state.

stdio is a local subprocess transport. The host sends newline-delimited JSON-RPC on stdin and reads stdout. Server logs belong on stderr. Streamable HTTP lets multiple clients reach a remote endpoint. In the modern revision each message uses POST, with responses as JSON or a request-scoped SSE stream. A client can request a longer-lived stream for supported change notifications through subscriptions/listen. Older HTTP+SSE transport and Streamable HTTP streaming are distinct.

The modern core lets replicas receive independent requests, removing transport session affinity. A draft ticket still belongs in a database. The server must authorize the caller against the draft on every access. Clients that need both protocol families should use a dual-era SDK and test each supported transport. Verify the host’s protocol support and the particular optional capabilities separately from the SDK package version.

Trace a call across the boundary

  1. The host uses tools/list to obtain names, descriptions, and schemas. It offers only the relevant, permitted subset to the model. If catalogs differ by user or tenant, keep them in authorization-scoped caches. Respect the server’s freshness hints.
  2. The model proposes a call to get_error_rate for checkout. The host selects the registered server, checks the approval policy and dispatches. The server validates identity and arguments before asking the backend for aggregates.
  3. It returns structured counts, not raw payloads or customer data. The host checks fields and provenance before including the small observation in the model’s context.

The following is an illustrative wire request for a modern server over Streamable HTTP. A protected deployment uses a transport credential supplied by the host.

The method selects the protocol operation. The name selects the registered tool. The response repeats the request ID so the client can correlate it.

POST /mcp HTTP/1.1
Host: monitoring.example
Content-Type: application/json
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: get_error_rate

{
  "jsonrpc": "2.0",
  "id": 42,
  "method": "tools/call",
  "params": {
    "name": "get_error_rate",
    "arguments": {"service": "checkout"},
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {}
    }
  }
}
Example tool response
{
  "jsonrpc": "2.0",
  "id": 42,
  "result": {
    "resultType": "complete",
    "content": [
      {
        "type": "text",
        "text": "5xx counts: 2 of 1000 before, 49 of 1000 after."
      }
    ],
    "structuredContent": {
      "before_5xx": 2,
      "before_requests": 1000,
      "after_5xx": 49,
      "after_requests": 1000
    },
    "isError": false
  }
}

At 16:10 the example closes two adjacent ten-minute windows, with 2 errors in 1,000 requests before release and 49 in 1,000 after. For a nonempty window:

The rise from 0.2% to 4.9% is 4.7 percentage points, or 24.5 times the earlier rate. With zero requests, report “no traffic” and leave the rate undefined. The counts are synthetic. In production, check whether errors concentrate in the new version and compare with dependency health, request mix, and a stable cohort. A jump after deployment prioritizes an investigation without establishing the release as the cause.

Authorization and data boundaries

There are three decisions: which tool the model can see, which action the host will dispatch, and which resource the server will authorize. The last decision depends on the verified caller and target, never on a tenant name volunteered by the model. A read-only annotation is a hint for the application. Enforce read-only access via the backend identity and allowed operations.

For protected Streamable HTTP servers, the MCP authorization specification describes the OAuth-based flow and resource discovery. Validate the token’s intended audience and issuer and enforce its scopes against the target. Use separately authorized credentials when invoking the monitoring or ticketing API. In a local stdio setup, review the executable and limit its accessible directories, environment variables, and network access.

Treat tool output, resource contents, and catalog descriptions supplied by third parties as external data. Pass bounded fields and their provenance to the model. Enforce budgets and access rules in application code. Approve a sensitive action against the exact operation, object and parameters, and expire that approval. Record the policy outcome and trace ID, with sensitive inputs excluded.

Failure, retry, and concurrency

Symptom Interpretation Handling
HTTP authorization failure Transport identity or access policy rejected the request. Check audience, scopes and caller policy. Keep the denial visible.
JSON-RPC error The request or method failed at the protocol layer. Check the version, schema, and registered method.
Tool result with isError: true The tool handled the invocation and reported a failure, such as an unsupported service. Preserve a useful error message and allow a bounded correction.
Client times out during a write The outcome is unknown, even when the socket closed. Reconcile with the downstream record before a retry.

JSON-RPC request IDs correlate messages. A business idempotency key correlates attempts to create the same ticket. Use a durable unique key scoped to the tenant and intended operation and store the outcome. If ticket creation is in a separate service, propagate a supported idempotency key or reconcile via a durable external identifier. A local transaction alone cannot make the external API atomic with the application database. Cancelling a call should stop outstanding work when possible. It cannot undo a committed mutation.

Measure discovery time and tool duration separately from model inference. Track timeouts, policy denials and uncertain write outcomes with a trace ID. In the case study, a working MCP request can still yield a misleading diagnosis if the monitoring query mixes deployment versions. Include evidence quality in review alongside availability.

Fit MCP into the rest of the stack

Layer Decision in the incident
Function calling Which named operation and arguments does the model propose?
MCP How does the host discover and invoke that capability across a standard boundary?
RAG Which passages of the runbooks are relevant, and which ones support the answer?
Agent runtime What executes next, how much time or cost is left, and when should it stop or ask the user?

A runbook search tool can use BM25, a vector index, or hybrid retrieval. MCP exposes the tool; the search implementation decides ranking. A deterministic runbook workflow can use the same MCP server without an autonomous agent. To minimize coupling, keep tool schemas domain-oriented, return explicit evidence fields, and keep the execution loop and its checkpoints in the host or workflow runtime.

Related tutorials

Practice and verification

Install Python 3.11 or later and pin the Python SDK in a virtual environment. The script launches itself as a subprocess over stdio and exercises catalog discovery, a resource, a rendered prompt, a successful tool call, and a rejected lookup. It uses deterministic fixtures, with no seed, model key or network access needed at runtime. The tested SDK implements the 2025-11-25 handshake. The modern wire example above is explanatory. The official SDK v2 documentation covers new integrations.

python -m venv .venv
. .venv/bin/activate
python -m pip install "mcp==1.29.0"
python mcp-sre-demo.py

Download the Python exercise

Show the full Python example
"""Local, read-only MCP exercise. Requires Python 3.11+ and mcp==1.29.0."""

import asyncio
from pathlib import Path
import sys

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError

server = FastMCP("sre-demo")
RUNBOOK = "runbook://checkout/5xx"


@server.resource(RUNBOOK)
def checkout_runbook() -> str:
    """Read the synthetic checkout runbook."""
    return "Compare 5xx rates by deployment version and time window."


@server.prompt()
def incident_summary() -> str:
    """Build a reusable prompt without executing a tool."""
    return "List the observations, competing hypotheses, and next check."


@server.tool()
def get_error_rate(service: str) -> dict[str, str | int]:
    """Read count data from two adjacent 10-minute windows."""
    if service != "checkout":
        raise ToolError("This fixture only provides checkout data.")
    return {
        "service": service,
        "before_start_utc": "2026-11-21T15:50:00Z",
        "after_start_utc": "2026-11-21T16:00:00Z",
        "after_end_utc": "2026-11-21T16:10:00Z",
        "before_requests": 1000,
        "after_requests": 1000,
        "before_5xx": 2,
        "after_5xx": 49,
    }


async def verify() -> None:
    command = StdioServerParameters(
        command=sys.executable, args=[str(Path(__file__).resolve()), "--serve"]
    )
    async with stdio_client(command) as (incoming, outgoing):
        async with ClientSession(incoming, outgoing) as client:
            session = await client.initialize()
            tools = await client.list_tools()
            assert [tool.name for tool in tools.tools] == ["get_error_rate"]

            runbook = await client.read_resource(RUNBOOK)
            assert "deployment version" in runbook.contents[0].text
            prompt = await client.get_prompt("incident_summary")
            assert "hypotheses" in prompt.messages[0].content.text

            result = await client.call_tool("get_error_rate", {"service": "checkout"})
            assert not result.isError and result.structuredContent is not None
            counts = result.structuredContent
            before = 100 * counts["before_5xx"] / counts["before_requests"]
            after = 100 * counts["after_5xx"] / counts["after_requests"]
            assert (before, after) == (0.2, 4.9)

            denied = await client.call_tool("get_error_rate", {"service": "billing"})
            assert denied.isError
            print(f"MCP {session.protocolVersion}")
            print(f"checkout: {before:.1f}% -> {after:.1f}% (+{after-before:.1f} pp)")
            print("Catalog, resource, prompt, tool result and denied lookup: PASS")


if __name__ == "__main__":
    if sys.argv[1:] == ["--serve"]:
        server.run(transport="stdio")
    else:
        asyncio.run(verify())

Expected output

MCP 2025-11-25
checkout: 0.2% -> 4.9% (+4.7 pp)
Catalog, resource, prompt, tool result and denied lookup: PASS

The test prints the protocol version, the exact change in 5xx rate, and PASS. For a fair comparison with a direct SDK integration, keep the fixture, caller grants, model and evidence budget fixed. Compare discovery, successful reads and failures separately. A stopwatch result on this local fixture cannot establish production throughput.

These interview exercises are original practice questions.

The catalog lists checkout, but the tool returns access denied. Where do you look?

Hint 1

Compare visibility with authorization.

Hint 2

Trace the authenticated caller, environment, tenant and target resource.

Answer and reasoning

Check the server’s resource-level decision and backend scope. The catalog describes a tool, and a valid payload still needs target authorization.

A write times out after a ticket was sent downstream. Can the host safely retry?

Hint 1

A timeout describes what the caller observed.

Hint 2

Separate the JSON-RPC ID from the ticket’s identity.

Answer and reasoning

Check the downstream record by the persisted business key. Retry only when the downstream service supports idempotency or evidence shows the write did not commit.

Your new client sends tools/call before initialize. The server rejects it. What do you check?

Hint 1

Identify the server’s supported protocol family.

Hint 2

Compare stdio and HTTP compatibility, including per-request metadata.

Answer and reasoning

Legacy servers need initialization. A modern server expects declared protocol metadata. Use a dual-era client for a mixed fleet and test both flows.

Self-assessment (1–5)

  1. Names the model, host, client and server.
  2. Traces discovery and dispatch of a successful call.
  3. Separates schema validation, authorization and protocol or tool errors.
  4. Explains both protocol versions and reconciles an uncertain write.
  5. Designs an auditable integration and verifies allowed, denied and failed paths with fixed fixtures.

Official sources and further reading