Skip to main content

Ask for more scope when a tool needs it

Start a client with basic scopes, and ask for one more when it calls a tool that needs it.

RecipeReadyView source
Works with
JavaScript / TypeScriptMCP TypeScript SDK

What it shows​

  1. The registration has two scopes, and one of them is a basic scope. The first challenge names only invoices:read.
  2. The client signs the person in with that scope and calls a tool.
  3. The refund tool declares the scopes that it needs. A call without them answers 403 insufficient_scope and names them.
  4. The client sends the person to LumoAuth again. The consent screen asks only for the new scope.
  5. The client calls the tool again with the new token.

Before you start​

  • An MCP server registered in LumoAuth, with http://localhost:3000/mcp as its resource URI, the scopes invoices:read and invoices:refund, and invoices:read as the basic scope. The setup script registers it.
  • An application for the client. The setup script creates Local MCP client: a public application with the redirect URI http://localhost:8765/callback. Its scopes include both scopes of the server.
  • A user of your organization who can sign in.
  • Node.js 20 or later.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:agents:read, admin:agents:write, admin:clients:read and admin:clients:write. Only the setup script reads it.
LUMOAUTH_MCP_SERVER_IDThe ID of the registered MCP server (mcp_…). The setup script prints it. The server reads it.
MCP_CLIENT_IDThe client ID of the application Local MCP client. The setup script prints it. The 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/scope-step-up/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, and a
// public application for the MCP client. Run it again at any time.
//
// node mcp-servers/scope-step-up/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write,
// admin:clients:read and admin:clients: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'],
// The challenge and the metadata name only the basic scopes. A client asks
// for invoices:refund when a tool needs it.
basic_scopes: ['invoices:read'],
// The MCP TypeScript SDK client of this recipe sends plain bearer tokens.
require_dpop: false,
});

// The client is a public application: it has no secret and uses PKCE. Its
// list of scopes must hold every scope that it may ever ask for.
const redirectUri = process.env.MCP_CLIENT_REDIRECT_URI ?? 'http://localhost:8765/callback';
const client = await ensure('/admin/clients', (c) => c.name === 'Local MCP client', {
name: 'Local MCP client',
isConfidential: false,
redirectUris: [redirectUri],
scopes: ['openid', 'profile', 'email', 'offline_access', 'invoices:read', 'invoices:refund'],
});

console.log(`MCP server ${server.name} (${server.resource_uri}) and the application "${client.name}" are ready.`);
printEnv({ LUMOAUTH_MCP_SERVER_ID: server.server_id, MCP_CLIENT_ID: client.clientId });

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.

mcp-servers/scope-step-up/js/server.mjs
// An MCP server where one tool needs a scope that is not in the basic set.
// A call without that scope gets 403 insufficient_scope, so that the client
// can ask the person for it.
//
// node mcp-servers/scope-step-up/js/server.mjs
//
// It listens on http://localhost:3000/mcp, the resource URI of the registration.
import { serve } from '@hono/node-server';
import { McpServer, createMcpHandler } from '@modelcontextprotocol/server';
import { lumoAuth } from '@lumoauth/mcp';
import { z } from 'zod';

const auth = lumoAuth();
await auth.ready();

const text = (value) => ({ content: [{ type: 'text', text: value }] });

const handler = createMcpHandler(() => {
const server = new McpServer({ name: 'invoices', version: '1.0.0' });

server.registerTool('list_invoices', { description: 'List the invoices.' }, async () =>
text(JSON.stringify([{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 }])),
);

// The tool declares the scopes that a call needs: the scope of every
// request, and its own. When the token lacks one, the SDK answers 403 with
// WWW-Authenticate: Bearer error="insufficient_scope", and names them all.
// The client then asks for a token that carries both.
server.registerTool(
'refund',
{
description: 'Refund one invoice.',
inputSchema: z.object({ invoiceId: z.string() }),
scopeChallenge: auth.scopeChallenge('invoices:read', 'invoices:refund'),
},
async ({ invoiceId }) => text(`Refunded ${invoiceId}`),
);

return server;
});

async function fetchHandler(request) {
const discovery = await auth.discovery(request);
if (discovery) return discovery;
// Every request needs the basic scope. The 401 challenge names it.
const authInfo = await auth.gate(request, { requiredScopes: ['invoices:read'] });
if (authInfo instanceof Response) return authInfo;
return handler.fetch(request, { authInfo });
}

serve({ fetch: fetchHandler, port: Number(process.env.PORT ?? 3000) });
mcp-servers/scope-step-up/js/client.mjs
// An MCP client that signs a person in with the basic scopes, and asks for
// one more scope when a tool needs it.
//
// node mcp-servers/scope-step-up/js/client.mjs
//
// Start the server first, in another terminal. The client prints an address
// two times. Open each in a browser, sign in and approve.
import http from 'node:http';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

const mcpUrl = process.env.MCP_URL ?? 'http://localhost:3000/mcp';
const redirectUri = process.env.MCP_CLIENT_REDIRECT_URI ?? 'http://localhost:8765/callback';

// The browser comes back to this address with the authorization code.
let deliverCode;
const callback = http.createServer((req, res) => {
const url = new URL(req.url, redirectUri);
if (url.pathname !== new URL(redirectUri).pathname) return res.writeHead(404).end();
res.end('You can close this window.');
deliverCode(url.searchParams.get('code'));
});
callback.listen(Number(new URL(redirectUri).port));
const nextCode = () => new Promise((resolve) => (deliverCode = resolve));

// What the SDK needs to run the authorization code flow with PKCE. This
// client keeps everything in memory.
let tokens;
let codeVerifier;
const provider = {
redirectUrl: redirectUri,
clientMetadata: { client_name: 'Local MCP client', redirect_uris: [redirectUri] },
clientInformation: () => ({ client_id: process.env.MCP_CLIENT_ID }),
tokens: () => tokens,
// The SDK tries a refresh before it asks the person again, and a refresh
// cannot add a scope. This client therefore keeps no refresh token.
saveTokens: ({ refresh_token, ...saved }) => {
tokens = saved;
console.log(`token: scope "${saved.scope}"`);
},
saveCodeVerifier: (verifier) => (codeVerifier = verifier),
codeVerifier: () => codeVerifier,
// The SDK built this address from the challenge of the server and from the
// metadata of LumoAuth. A desktop client opens the browser here.
redirectToAuthorization: (url) => console.log(`authorize: scope "${url.searchParams.get('scope')}"\n open ${url}`),
};

const newTransport = () => new StreamableHTTPClientTransport(new URL(mcpUrl), { authProvider: provider });
const client = new Client({ name: 'local-mcp-client', version: '1.0.0' });

// 1. The first request has no token. The 401 challenge names the basic
// scopes, and the SDK starts an authorization request for them.
let transport = newTransport();
try {
await client.connect(transport);
} catch (error) {
if (!(error instanceof UnauthorizedError)) throw error;
await transport.finishAuth(await nextCode());
// A transport starts only once, so the client connects with a new one.
transport = newTransport();
await client.connect(transport);
}

const invoices = await client.callTool({ name: 'list_invoices' });
console.log('list_invoices:', invoices.content[0].text);

// 2. The refund needs invoices:refund. The server answers 403
// insufficient_scope, and the SDK starts a second authorization request.
const call = { name: 'refund', arguments: { invoiceId: 'INV-1001' } };
let refund;
try {
refund = await client.callTool(call);
} catch (error) {
if (!(error instanceof UnauthorizedError)) throw error;
await transport.finishAuth(await nextCode());
refund = await client.callTool(call);
}
console.log('refund:', refund.content[0].text);

await client.close();
callback.close();
node mcp-servers/scope-step-up/js/server.mjs
# In a second terminal:
node mcp-servers/scope-step-up/js/client.mjs

A headless browser played the person: it signed in and approved both consent screens.

The server uses @modelcontextprotocol/server, where registerTool takes a scopeChallenge. The client uses the OAuth support of @modelcontextprotocol/sdk.

Check the result​

Output
authorize: scope "invoices:read"
open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?response_type=code&client_id=client_8b1c…&scope=invoices%3Aread&resource=http%3A%2F%2Flocalhost%3A3000%2Fmcp&…
token: scope "invoices:read"
list_invoices: [{"id":"INV-1001","customer":"Northwind Labs","amount":1200}]
authorize: scope "invoices:read invoices:refund"
open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?response_type=code&client_id=client_8b1c…&scope=invoices%3Aread+invoices%3Arefund&resource=http%3A%2F%2Flocalhost%3A3000%2Fmcp&…
token: scope "invoices:read invoices:refund"
refund: Refunded INV-1001
  • The first consent screen names the server and lists invoices:read.
  • The second consent screen lists invoices:refund, and shows invoices:read under "Already granted".
  • Run the client again as the same person: LumoAuth shows no consent screen, because the person approved both scopes for this application and this server.
  • Call the server by hand with the first token to see the challenge of step 3:
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", error_description="Insufficient scope", scope="invoices:read invoices:refund", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"

Limits​

  • An application can only ask for scopes on its own list. Add a new scope in two places: the scopes of the MCP server, and the scopes of each application that may ask for it.
  • The client of this recipe keeps no refresh token. The SDK tries a refresh before it asks the person again, and a refresh cannot add a scope.
  • The new token carries the scopes that the client asked for. That is why the challenge names both scopes, not only the missing one.
  • scopeChallenge belongs to @modelcontextprotocol/server. With @modelcontextprotocol/sdk, auth.guard() refuses the call inside the tool result: see Protect a server built on the MCP TypeScript SDK.