VereskLearn

Module 7 · MCP

Lesson 7.4

HTTP transport and tokens

The HTTP transport lets a server run on a network, and a token shows which client is calling.

Lesson 48 of 622 min read

The problem

Why it matters

Without it

A server on a network accepts any caller. Anyone who finds its address can run its tools.

With it

Each request carries a bearer token. The server checks the token and allows only the methods it may use.

How it works

  • Messages travel in HTTP bodies

    Each JSON message is sent in the body of an HTTP request. The server returns its JSON reply in the response body. The messages are the same as the ones sent over standard input.

    1. Client sends POST
    2. Authorization header
    3. Server checks token
    4. JSON reply
    One request and its reply over HTTP.
  • The token names the caller

    The client adds an Authorization header with the word Bearer and a secret token. The server looks the token up to find the caller. An unknown token is refused before any method runs.

    const tokens = new Map([["svc-reader-7f3a", "reader"]]);const header = "Bearer svc-reader-7f3a";const caller = tokens.get(header.replace("Bearer ", ""));console.log("Caller: " + caller);

    Output

    Caller: reader
  • Status codes give the outcome

    401 means the token is missing or unknown. 403 means the token is known, but the method is not allowed. 200 means the call worked.

    RequestTokenMethodStatus
    1nonetools/list401
    2readertools/list200
    3readerresources/read403
    Three requests and their status codes.
  • Each token has its own methods

    The server keeps a list of allowed methods for each token. The reader token may list and call tools, but it may not read resources. Give each client only the methods it needs.

    Allowed for the reader token

    • tools/list
    • tools/call

    Refused for the reader token

    • resources/read, status 403
    What the reader token may call, and what it may not.

Full code

Read the program

See the full code

Common mistakes

What goes wrong

  • Sending tokens over plain HTTP. Anyone on the network path can read the header.
  • Storing tokens as plain text. A leaked table then exposes every token.
  • Giving every token every method. Give each token only the methods its client needs.

Use it when and skip it when

Is it the right tool?

Use it when

  • The server runs on a network and more than one client connects.
  • Different clients need different rights.

Skip it when

  • The server runs only on your own machine, over standard input.

Words to know

Terms in this lesson

Transport
The way messages travel between client and server, such as standard input or HTTP.
Bearer token
A secret string sent in a header that proves who is calling.
Authorization header
The HTTP header that carries the token.
Status code
A number in an HTTP reply that gives the outcome, such as 200 for success.
Full code