An MCP server with no LumoAuth package
Write the three parts by hand, in any language: the metadata document, the 401 challenge and the token check.
What it shows
- At start, the server reads the metadata that LumoAuth publishes for its registration. It serves the same document at
/.well-known/oauth-protected-resource/mcp, where MCP clients look for it. - It reads the metadata of the issuer, checks that the issuer matches, and takes the address of the key set from it.
- A request without a token gets
401, with aWWW-Authenticateheader that names the metadata and the basic scopes. - The server verifies each token: the signature with the key set, the type
at+jwt, the issuer, the audience and the expiry. - Each tool needs a scope. A valid token without it gets
403witherror="insufficient_scope"and the missing scope.
Each server uses only an HTTP framework and a JWT library. It answers the MCP messages initialize, tools/list and tools/call by hand, with no MCP package.
Before you start
- An MCP server registered in LumoAuth, and an agent for the test client. The setup script registers
Invoicesathttp://localhost:3000/mcp, withinvoices:readas its basic scope. It creates the agentinvoice-reader, which holdsinvoices:readand notinvoices:refund. - Node.js 20 or later, Python 3.10 or later, or Go 1.22 or later. The test client needs
curlandjq.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scopes admin:agents:read and admin:agents:write. The setup script and the test client read it. The servers do not. |
LUMOAUTH_MCP_SERVER_ID | The ID of the registered MCP server (mcp_…). The setup script prints it. The servers read it. |
MCP_AGENT_ID | The ID of the test agent (agt_…). The setup script prints it. The test client reads it. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node mcp-servers/without-a-package/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, and an
// agent that may read invoices. Run it again at any time.
//
// node mcp-servers/without-a-package/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { ensure, printEnv } from '../../_lib/admin.mjs';
// The resource URI is the exact address that clients connect to.
const resource = process.env.MCP_RESOURCE_URI ?? 'http://localhost:3000/mcp';
const server = await ensure('/admin/mcp/servers', (s) => s.resource_uri === resource, {
name: 'Invoices',
description: 'Reads and refunds invoices.',
resource_uri: resource,
endpoint_url: resource,
scopes_supported: ['invoices:read', 'invoices:refund'],
// A client asks for the basic scopes first. The challenge names only these.
basic_scopes: ['invoices:read'],
// The test client of this recipe sends plain bearer tokens.
require_dpop: false,
});
// The agent holds invoices:read and not invoices:refund.
const agent = await ensure('/admin/agents', (a) => a.name === 'invoice-reader', {
name: 'invoice-reader',
description: 'Reads invoices through the Invoices MCP server.',
capabilities: ['invoices:read'],
});
console.log(`MCP server ${server.name} (${server.resource_uri}) and agent ${agent.name} are ready.`);
printEnv({ LUMOAUTH_MCP_SERVER_ID: server.server_id, MCP_AGENT_ID: agent.agentId });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Each server ran with the curl test client. Each one was also called by the client of the MCP TypeScript SDK and by lumo mcp test, and refused a token that was issued for another MCP server.
- Node.js and jose
- FastAPI and PyJWT
- net/http and jwx
- Test client (curl)
// An MCP server with no LumoAuth package: Node's HTTP server and the JWT
// library jose. It serves the metadata, answers with the 401 challenge,
// verifies each token and checks the scope of each tool.
//
// node mcp-servers/without-a-package/js/server.mjs
//
// It listens on http://localhost:3000/mcp, the resource URI of the registration.
import http from 'node:http';
import { createRemoteJWKSet, jwtVerify } from 'jose';
const lumoauthUrl = (process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '');
const issuer = `${lumoauthUrl}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
const getJson = async (url) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url} answered ${response.status}`);
return response.json();
};
// 1. LumoAuth publishes the metadata of the registration. This server serves
// the same document at its own address, where MCP clients look for it.
const metadata = await getJson(`${issuer}/.well-known/oauth-protected-resource/mcp/${process.env.LUMOAUTH_MCP_SERVER_ID}`);
const resource = new URL(metadata.resource);
const metadataPath = `/.well-known/oauth-protected-resource${resource.pathname}`;
const metadataUrl = `${resource.origin}${metadataPath}`;
// The issuer's own metadata names the key set. Never build that path yourself.
const { origin, pathname } = new URL(issuer);
const server = await getJson(`${origin}/.well-known/oauth-authorization-server${pathname}`);
if (server.issuer !== issuer) throw new Error(`The metadata names the issuer ${server.issuer}, not ${issuer}.`);
const keys = createRemoteJWKSet(new URL(server.jwks_uri));
const invoices = [
{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 },
{ id: 'INV-1002', customer: 'Acme', amount: 300 },
];
const tools = {
list_invoices: { scope: 'invoices:read', run: () => invoices.map((i) => `${i.id} ${i.customer} ${i.amount}`).join(', ') },
refund: { scope: 'invoices:refund', run: (args) => `Refunded ${args.invoice_id}` },
};
// Scopes compare exactly. LumoAuth adds one rule: a granted scope that ends
// in ":*" covers the scopes under it.
const covered = (needed, granted) =>
granted.some((g) => g === needed || (g.endsWith(':*') && g !== ':*' && needed.startsWith(g.slice(0, -1))));
function send(res, status, body, headers = {}) {
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
res.end(body === undefined ? undefined : JSON.stringify(body));
}
// 2. A request without a valid token gets 401, with the address of the metadata.
function challenge(res, status, error, description, scope) {
const parts = [];
if (error) parts.push(`error="${error}"`);
if (description) parts.push(`error_description="${description}"`);
parts.push(`resource_metadata="${metadataUrl}"`);
parts.push(`scope="${scope ?? metadata.scopes_supported.join(' ')}"`);
send(res, status, { error: error ?? 'invalid_request' }, { 'WWW-Authenticate': `Bearer ${parts.join(', ')}` });
}
// 3. The token check: signature from the key set, type, issuer, audience, expiry.
async function verify(token) {
const { payload } = await jwtVerify(token, keys, { issuer, audience: metadata.resource, typ: 'at+jwt' });
return payload;
}
http
.createServer(async (req, res) => {
if (req.method === 'GET' && req.url === metadataPath) return send(res, 200, metadata);
if (req.url !== resource.pathname) return send(res, 404, { error: 'not_found' });
if (req.method !== 'POST') return send(res, 405, { error: 'method_not_allowed' });
// A browser page of another site must not reach a server on your machine.
if (req.headers.origin && req.headers.origin !== resource.origin) return send(res, 403, { error: 'origin_not_allowed' });
const bearer = /^Bearer (.+)$/i.exec(req.headers.authorization ?? '')?.[1];
if (!bearer) return challenge(res, 401);
let claims;
try {
claims = await verify(bearer);
} catch {
return challenge(res, 401, 'invalid_token', 'the token is not valid for this server');
}
let body = '';
for await (const chunk of req) body += chunk;
const message = JSON.parse(body);
if (message.id === undefined) return send(res, 202);
const reply = (result) => send(res, 200, { jsonrpc: '2.0', id: message.id, result });
if (message.method === 'initialize') {
return reply({
protocolVersion: message.params.protocolVersion,
capabilities: { tools: {} },
serverInfo: { name: 'invoices', version: '1.0.0' },
});
}
if (message.method === 'tools/list') {
return reply({
tools: Object.keys(tools).map((name) => ({
name,
inputSchema: name === 'refund'
? { type: 'object', properties: { invoice_id: { type: 'string' } }, required: ['invoice_id'] }
: { type: 'object', properties: {} },
})),
});
}
if (message.method === 'tools/call') {
const tool = tools[message.params.name];
if (!tool) return send(res, 200, { jsonrpc: '2.0', id: message.id, error: { code: -32602, message: 'Unknown tool' } });
// 4. The scope of the tool. A valid token without it gets 403, which
// names the scope, so that the client can ask the person for it.
const granted = (claims.scope ?? '').split(' ');
if (!covered(tool.scope, granted)) return challenge(res, 403, 'insufficient_scope', undefined, tool.scope);
return reply({ content: [{ type: 'text', text: tool.run(message.params.arguments ?? {}) }] });
}
send(res, 200, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } });
})
.listen(Number(process.env.PORT ?? 3000));
node mcp-servers/without-a-package/js/server.mjs
# In a second terminal:
sh mcp-servers/without-a-package/http/check.sh
"""An MCP server with no LumoAuth package: FastAPI and the JWT library PyJWT.
It serves the metadata, answers with the 401 challenge, verifies each token
and checks the scope of each tool.
python mcp-servers/without-a-package/python/server.py
It listens on http://localhost:3000/mcp, the resource URI of the registration.
"""
import os
from urllib.parse import urlsplit
import jwt
import requests
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
LUMOAUTH_URL = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev").rstrip("/")
ISSUER = f"{LUMOAUTH_URL}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
def get_json(url: str) -> dict:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
# 1. LumoAuth publishes the metadata of the registration. This server serves
# the same document at its own address, where MCP clients look for it.
METADATA = get_json(f"{ISSUER}/.well-known/oauth-protected-resource/mcp/{os.environ['LUMOAUTH_MCP_SERVER_ID']}")
RESOURCE = urlsplit(METADATA["resource"])
ORIGIN = f"{RESOURCE.scheme}://{RESOURCE.netloc}"
METADATA_PATH = f"/.well-known/oauth-protected-resource{RESOURCE.path}"
METADATA_URL = ORIGIN + METADATA_PATH
# The issuer's own metadata names the key set. Never build that path yourself.
_issuer = urlsplit(ISSUER)
SERVER = get_json(f"{_issuer.scheme}://{_issuer.netloc}/.well-known/oauth-authorization-server{_issuer.path}")
if SERVER["issuer"] != ISSUER:
raise SystemExit(f"The metadata names the issuer {SERVER['issuer']}, not {ISSUER}.")
KEYS = jwt.PyJWKClient(SERVER["jwks_uri"])
INVOICES = [
{"id": "INV-1001", "customer": "Northwind Labs", "amount": 1200},
{"id": "INV-1002", "customer": "Acme", "amount": 300},
]
TOOLS = {
"list_invoices": ("invoices:read", lambda args: ", ".join(f"{i['id']} {i['customer']} {i['amount']}" for i in INVOICES)),
"refund": ("invoices:refund", lambda args: f"Refunded {args['invoice_id']}"),
}
SCHEMAS = {
"list_invoices": {"type": "object", "properties": {}},
"refund": {"type": "object", "properties": {"invoice_id": {"type": "string"}}, "required": ["invoice_id"]},
}
def covered(needed: str, granted: list[str]) -> bool:
# Scopes compare exactly. LumoAuth adds one rule: a granted scope that
# ends in ":*" covers the scopes under it.
return any(g == needed or (g.endswith(":*") and g != ":*" and needed.startswith(g[:-1])) for g in granted)
def challenge(status: int, error: str | None = None, description: str | None = None, scope: str | None = None):
"""2. A request without a valid token gets 401, with the address of the metadata."""
parts = [f'error="{error}"'] if error else []
if description:
parts.append(f'error_description="{description}"')
parts.append(f'resource_metadata="{METADATA_URL}"')
parts.append(f'scope="{scope or " ".join(METADATA["scopes_supported"])}"')
return JSONResponse({"error": error or "invalid_request"}, status, headers={"WWW-Authenticate": "Bearer " + ", ".join(parts)})
def verify(token: str) -> dict:
"""3. The token check: signature from the key set, type, issuer, audience, expiry."""
if jwt.get_unverified_header(token).get("typ") != "at+jwt":
raise jwt.InvalidTokenError("not an access token")
key = KEYS.get_signing_key_from_jwt(token)
return jwt.decode(token, key, algorithms=["RS256", "ES256", "EdDSA"], audience=METADATA["resource"],
issuer=ISSUER, options={"require": ["exp", "iss", "aud", "sub"]})
app = FastAPI()
@app.get(METADATA_PATH)
def metadata():
return METADATA
@app.post(RESOURCE.path)
async def mcp(request: Request):
# A browser page of another site must not reach a server on your machine.
origin = request.headers.get("origin")
if origin and origin != ORIGIN:
return JSONResponse({"error": "origin_not_allowed"}, 403)
authorization = request.headers.get("authorization", "")
if not authorization.lower().startswith("bearer "):
return challenge(401)
try:
claims = verify(authorization[7:])
except jwt.PyJWTError:
return challenge(401, "invalid_token", "the token is not valid for this server")
message = await request.json()
if "id" not in message:
return Response(status_code=202)
def reply(result: dict):
return {"jsonrpc": "2.0", "id": message["id"], "result": result}
params = message.get("params") or {}
if message["method"] == "initialize":
return reply({
"protocolVersion": params.get("protocolVersion"),
"capabilities": {"tools": {}},
"serverInfo": {"name": "invoices", "version": "1.0.0"},
})
if message["method"] == "tools/list":
return reply({"tools": [{"name": name, "inputSchema": SCHEMAS[name]} for name in TOOLS]})
if message["method"] == "tools/call":
if params.get("name") not in TOOLS:
return {"jsonrpc": "2.0", "id": message["id"], "error": {"code": -32602, "message": "Unknown tool"}}
scope, run = TOOLS[params["name"]]
# 4. The scope of the tool. A valid token without it gets 403, which
# names the scope, so that the client can ask the person for it.
if not covered(scope, claims.get("scope", "").split()):
return challenge(403, "insufficient_scope", scope=scope)
return reply({"content": [{"type": "text", "text": run(params.get("arguments") or {})}]})
return {"jsonrpc": "2.0", "id": message["id"], "error": {"code": -32601, "message": "Method not found"}}
@app.get(RESOURCE.path)
def no_stream():
return Response(status_code=405)
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=int(os.environ.get("PORT", "3000")))
python mcp-servers/without-a-package/python/server.py
# In a second terminal:
sh mcp-servers/without-a-package/http/check.sh
// An MCP server with no LumoAuth package: Go's net/http and the JWT library
// lestrrat-go/jwx. It serves the metadata, answers with the 401 challenge,
// verifies each token and checks the scope of each tool.
//
// go run ./mcp-servers/without-a-package/go
//
// It listens on http://localhost:3000/mcp, the resource URI of the registration.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jws"
"github.com/lestrrat-go/jwx/v2/jwt"
)
type tool struct {
scope string
schema map[string]any
run func(args map[string]any) string
}
var tools = map[string]tool{
"list_invoices": {"invoices:read", map[string]any{"type": "object", "properties": map[string]any{}},
func(map[string]any) string { return "INV-1001 Northwind Labs 1200, INV-1002 Acme 300" }},
"refund": {"invoices:refund", map[string]any{"type": "object", "properties": map[string]any{"invoice_id": map[string]any{"type": "string"}}, "required": []string{"invoice_id"}},
func(args map[string]any) string { return fmt.Sprintf("Refunded %v", args["invoice_id"]) }},
}
func getJSON(target string, into any) {
response, err := http.Get(target)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
log.Fatalf("%s answered %d", target, response.StatusCode)
}
if err := json.NewDecoder(response.Body).Decode(into); err != nil {
log.Fatal(err)
}
}
// covered compares scopes exactly. LumoAuth adds one rule: a granted scope
// that ends in ":*" covers the scopes under it.
func covered(needed string, granted []string) bool {
for _, g := range granted {
if g == needed || (strings.HasSuffix(g, ":*") && g != ":*" && strings.HasPrefix(needed, strings.TrimSuffix(g, "*"))) {
return true
}
}
return false
}
func main() {
ctx := context.Background()
lumoauthURL := strings.TrimRight(os.Getenv("LUMOAUTH_URL"), "/")
if lumoauthURL == "" {
lumoauthURL = "https://app.lumoauth.dev"
}
issuer := lumoauthURL + "/orgs/" + os.Getenv("LUMOAUTH_ORG_ID") + "/api/v1"
// 1. LumoAuth publishes the metadata of the registration. This server
// serves the same document at its own address, where MCP clients look for it.
var metadata map[string]any
getJSON(issuer+"/.well-known/oauth-protected-resource/mcp/"+os.Getenv("LUMOAUTH_MCP_SERVER_ID"), &metadata)
resourceURI := metadata["resource"].(string)
resource, _ := url.Parse(resourceURI)
metadataPath := "/.well-known/oauth-protected-resource" + resource.Path
metadataURL := resource.Scheme + "://" + resource.Host + metadataPath
var basic []string
for _, s := range metadata["scopes_supported"].([]any) {
basic = append(basic, s.(string))
}
// The issuer's own metadata names the key set. Never build that path yourself.
issuerURL, _ := url.Parse(issuer)
var server struct {
Issuer string `json:"issuer"`
JWKSURI string `json:"jwks_uri"`
}
getJSON(issuerURL.Scheme+"://"+issuerURL.Host+"/.well-known/oauth-authorization-server"+issuerURL.Path, &server)
if server.Issuer != issuer {
log.Fatalf("The metadata names the issuer %s, not %s.", server.Issuer, issuer)
}
cache := jwk.NewCache(ctx)
if err := cache.Register(server.JWKSURI); err != nil {
log.Fatal(err)
}
keys := jwk.NewCachedSet(cache, server.JWKSURI)
send := func(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(body)
}
// 2. A request without a valid token gets 401, with the address of the metadata.
challenge := func(w http.ResponseWriter, status int, errorCode, description, scope string) {
var parts []string
if errorCode != "" {
parts = append(parts, fmt.Sprintf(`error="%s"`, errorCode))
}
if description != "" {
parts = append(parts, fmt.Sprintf(`error_description="%s"`, description))
}
if scope == "" {
scope = strings.Join(basic, " ")
}
parts = append(parts, fmt.Sprintf(`resource_metadata="%s"`, metadataURL), fmt.Sprintf(`scope="%s"`, scope))
w.Header().Set("WWW-Authenticate", "Bearer "+strings.Join(parts, ", "))
if errorCode == "" {
errorCode = "invalid_request"
}
send(w, status, map[string]string{"error": errorCode})
}
// 3. The token check: signature from the key set, type, issuer, audience, expiry.
verify := func(token string) (jwt.Token, error) {
message, err := jws.Parse([]byte(token))
if err != nil {
return nil, err
}
if message.Signatures()[0].ProtectedHeaders().Type() != "at+jwt" {
return nil, fmt.Errorf("not an access token")
}
return jwt.Parse([]byte(token), jwt.WithKeySet(keys), jwt.WithValidate(true),
jwt.WithIssuer(issuer), jwt.WithAudience(resourceURI))
}
mux := http.NewServeMux()
mux.HandleFunc("GET "+metadataPath, func(w http.ResponseWriter, r *http.Request) { send(w, http.StatusOK, metadata) })
mux.HandleFunc(resource.Path, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
send(w, http.StatusMethodNotAllowed, map[string]string{"error": "method_not_allowed"})
return
}
// A browser page of another site must not reach a server on your machine.
if origin := r.Header.Get("Origin"); origin != "" && origin != resource.Scheme+"://"+resource.Host {
send(w, http.StatusForbidden, map[string]string{"error": "origin_not_allowed"})
return
}
bearer, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !found || bearer == "" {
challenge(w, http.StatusUnauthorized, "", "", "")
return
}
claims, err := verify(bearer)
if err != nil {
challenge(w, http.StatusUnauthorized, "invalid_token", "the token is not valid for this server", "")
return
}
var message struct {
ID any `json:"id"`
Method string `json:"method"`
Params struct {
ProtocolVersion string `json:"protocolVersion"`
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
} `json:"params"`
}
if err := json.NewDecoder(r.Body).Decode(&message); err != nil {
send(w, http.StatusBadRequest, map[string]string{"error": "parse_error"})
return
}
if message.ID == nil {
w.WriteHeader(http.StatusAccepted)
return
}
reply := func(result any) {
send(w, http.StatusOK, map[string]any{"jsonrpc": "2.0", "id": message.ID, "result": result})
}
fail := func(code int, text string) {
send(w, http.StatusOK, map[string]any{"jsonrpc": "2.0", "id": message.ID, "error": map[string]any{"code": code, "message": text}})
}
switch message.Method {
case "initialize":
reply(map[string]any{
"protocolVersion": message.Params.ProtocolVersion,
"capabilities": map[string]any{"tools": map[string]any{}},
"serverInfo": map[string]any{"name": "invoices", "version": "1.0.0"},
})
case "tools/list":
list := []map[string]any{}
for _, name := range []string{"list_invoices", "refund"} {
list = append(list, map[string]any{"name": name, "inputSchema": tools[name].schema})
}
reply(map[string]any{"tools": list})
case "tools/call":
t, ok := tools[message.Params.Name]
if !ok {
fail(-32602, "Unknown tool")
return
}
// 4. The scope of the tool. A valid token without it gets 403, which
// names the scope, so that the client can ask the person for it.
scope, _ := claims.Get("scope")
text, _ := scope.(string)
if !covered(t.scope, strings.Fields(text)) {
challenge(w, http.StatusForbidden, "insufficient_scope", "", t.scope)
return
}
reply(map[string]any{"content": []map[string]any{{"type": "text", "text": t.run(message.Params.Arguments)}}})
default:
fail(-32601, "Method not found")
}
})
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Fatal(http.ListenAndServe("localhost:"+port, mux))
}
go run ./mcp-servers/without-a-package/go
# In a second terminal:
sh mcp-servers/without-a-package/http/check.sh
#!/bin/sh
# Calls an MCP server three ways with curl: without a token, with the token of
# an agent, and for a tool that the token does not cover. It works against
# each server of this recipe.
#
# sh mcp-servers/without-a-package/http/check.sh
#
# Start a server first, in another terminal. Needs curl and jq.
set -eu
MCP_URL="${MCP_URL:-http://localhost:3000/mcp}"
API="${LUMOAUTH_URL:-https://app.lumoauth.dev}/orgs/$LUMOAUTH_ORG_ID/api/v1"
# 1. Without a token, the server answers 401 and says where its metadata is.
headers=$(curl -s -o /dev/null -D - -X POST "$MCP_URL" \
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | tr -d '\r')
status=$(printf '%s\n' "$headers" | head -n 1 | cut -d ' ' -f 2)
challenge=$(printf '%s\n' "$headers" | sed -n 's/^[Ww][Ww][Ww]-[Aa]uthenticate: //p')
echo "no token: $status $challenge"
# The metadata names the resource. A token must be issued for exactly that resource.
metadata_url=$(printf '%s' "$challenge" | sed 's/.*resource_metadata="\([^"]*\)".*/\1/')
resource=$(curl -s "$metadata_url" | jq -r .resource)
# 2. A test token of the agent from the Admin API. An agent that runs by itself
# asks the token endpoint with its own credential instead.
token=$(curl -s -X POST "$API/admin/agents/$MCP_AGENT_ID/token" \
-H "X-API-Key: $LUMOAUTH_API_KEY" -H 'Content-Type: application/json' \
-d "{\"resource\":\"$resource\",\"expiresIn\":300}" | jq -r .data.accessToken)
# One JSON-RPC request with the token. More curl options may follow the body.
rpc() {
body=$1
shift
curl -s -X POST "$MCP_URL" -H "Authorization: Bearer $token" \
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$body" "$@"
}
echo "tools: $(rpc '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | jq -r '[.result.tools[].name] | sort | join(", ")')"
echo "list_invoices: $(rpc '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_invoices","arguments":{}}}' | jq -r '.result.content[0].text')"
# 3. The agent holds invoices:read only. The refund needs invoices:refund, so
# the server answers 403 and names the missing scope.
refund=$(rpc '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"refund","arguments":{"invoice_id":"INV-1001"}}}' -o /dev/null -D - | tr -d '\r')
echo "refund: $(printf '%s\n' "$refund" | head -n 1 | cut -d ' ' -f 2) $(printf '%s\n' "$refund" | sed -n 's/^[Ww][Ww][Ww]-[Aa]uthenticate: //p')"
sh mcp-servers/without-a-package/http/check.sh
The three servers behave the same, so one test client works for all of them. Start one server, then run the test client in a second terminal.
Check the result
no token: 401 Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp", scope="invoices:read"
tools: list_invoices, refund
list_invoices: INV-1001 Northwind Labs 1200, INV-1002 Acme 300
refund: 403 Bearer error="insufficient_scope", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp", scope="invoices:refund"
- The first line is the challenge. An MCP client reads
resource_metadata, and from that document it finds LumoAuth. The server needs no other setting for that. - Open
http://localhost:3000/.well-known/oauth-protected-resource/mcpin a browser. It shows the resource, the issuer of your organization and the basic scopes. - The last line names
invoices:refund. An MCP client that signs a person in can ask for that scope and try again: see Ask for more scope when a tool needs it. - The servers also work with the client of the MCP TypeScript SDK, and with
lumo mcp test <server-id> <agent-id>.
Limits
- The servers accept only bearer tokens. For a registration with Require DPoP sender-constrained tokens on, the server must also check a proof on each request, as described in the server guide. The DPoP recipe uses the packages for that.
- A signature check cannot show that a token was revoked before it expires. Before an action that matters, ask LumoAuth with token introspection.
- The servers read the metadata once, at start. Restart a server after you change the registration.
- The MCP handling is the smallest part that a client needs: one JSON answer for each request, no stream, no notifications to the client. For more, use an MCP SDK with the TypeScript package or FastMCP.