Authorize from your own agent
The User Portal runs this flow for its users automatically. Build it yourself when your agent, CLI or chat client calls an OAuth-backed MCP server for a person. You need:
| Input | Where it comes from | Example |
|---|---|---|
| Gateway base URL | Your Core Proxy | http://localhost:8100 |
| MCP server ID and IdP ID | Admin UI, MCP server and Identity Provider records | mcp-system-hubspot-default, idp-system-hubspot-default |
| Client ID | The OAuth App Client linked to the server’s access configuration | 03012b66-5c17-4d7c-9297-39d9eb6c7c7f |
| Redirect URI | A loopback listener in your agent, registered at the provider | http://localhost:8085/callback |
| API key | A Brutor API key whose resource group may use the MCP server | sk_brutor_api_3f9c... |
The examples use these shell variables:
GW=http://localhost:8100OAUTH=$GW/v1/proxy/oauth/mcp-system-hubspot-default/idp-system-hubspot-defaultAPI_KEY=sk_brutor_api_3f9c...1. Discover the endpoints
Section titled “1. Discover the endpoints”Both documents are public. The protected-resource metadata names the facade as the authorization server; the OIDC document gives the authorize and token endpoints.
curl -s "$OAUTH/.well-known/oauth-protected-resource"curl -s "$OAUTH/.well-known/openid-configuration"import httpx
GW = "http://localhost:8100"OAUTH = f"{GW}/v1/proxy/oauth/mcp-system-hubspot-default/idp-system-hubspot-default"
prm = httpx.get(f"{OAUTH}/.well-known/oauth-protected-resource").json()issuer = prm["authorization_servers"][0]oidc = httpx.get(f"{issuer}/.well-known/openid-configuration").json()authorize_url, token_url = oidc["authorization_endpoint"], oidc["token_endpoint"]const GW = "http://localhost:8100";const OAUTH = `${GW}/v1/proxy/oauth/mcp-system-hubspot-default/idp-system-hubspot-default`;
const prm = await (await fetch(`${OAUTH}/.well-known/oauth-protected-resource`)).json();const issuer = prm.authorization_servers[0];const oidc = await (await fetch(`${issuer}/.well-known/openid-configuration`)).json();const { authorization_endpoint: authorizeUrl, token_endpoint: tokenUrl } = oidc;{ "resource": "https://mcp.hubspot.com", "authorization_servers": ["http://localhost:8100/v1/proxy/oauth/mcp-system-hubspot-default/idp-system-hubspot-default"], "bearer_methods_supported": ["header"], "scopes_supported": ["oauth", "crm.objects.tickets.read", "crm.objects.contacts.read", "crm.objects.companies.read"]}The OIDC document is shown in full on Configure.
resource is the upstream server’s base_url; scopes_supported falls back to
["openid", "profile", "email"] when the IdP lists none.
2. Get the user’s consent
Section titled “2. Get the user’s consent”Open the user’s browser at the facade’s authorization_endpoint. For a registered
client_id the gateway answers 307 to the IdP’s own authorize URL with your query string
unchanged, and the IdP redirects back to your redirect_uri.
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n' | cut -c1-64)CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=\n')open "$OAUTH/authorize?response_type=code&client_id=03012b66-5c17-4d7c-9297-39d9eb6c7c7f\&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2Fcallback&scope=oauth%20crm.objects.contacts.read\&state=8f2c1e&code_challenge=$CHALLENGE&code_challenge_method=S256"# After consent the browser lands on http://localhost:8085/callback?code=...&state=8f2c1eimport base64, hashlib, secrets, urllib.parse, webbrowserfrom http.server import BaseHTTPRequestHandler, HTTPServer
CLIENT_ID = "03012b66-5c17-4d7c-9297-39d9eb6c7c7f"REDIRECT_URI = "http://localhost:8085/callback"
verifier = secrets.token_urlsafe(48)challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()state = secrets.token_urlsafe(16)
webbrowser.open(authorize_url + "?" + urllib.parse.urlencode({ "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "scope": "oauth crm.objects.contacts.read", "state": state, "code_challenge": challenge, "code_challenge_method": "S256",}))
result = {}class Callback(BaseHTTPRequestHandler): def do_GET(self): result.update(urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)) self.send_response(200); self.end_headers() self.wfile.write(b"Authorized. You can close this window.")
HTTPServer(("localhost", 8085), Callback).handle_request()assert result["state"][0] == statecode = result["code"][0]import { createHash, randomBytes } from "node:crypto";import { createServer } from "node:http";import { exec } from "node:child_process";
const CLIENT_ID = "03012b66-5c17-4d7c-9297-39d9eb6c7c7f";const REDIRECT_URI = "http://localhost:8085/callback";
const verifier = randomBytes(48).toString("base64url");const challenge = createHash("sha256").update(verifier).digest("base64url");const state = randomBytes(16).toString("base64url");
const url = `${authorizeUrl}?${new URLSearchParams({ response_type: "code", client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, scope: "oauth crm.objects.contacts.read", state, code_challenge: challenge, code_challenge_method: "S256",})}`;exec(`open "${url}"`); // xdg-open on Linux, start on Windows
const code = await new Promise((resolve) => { const server = createServer((req, res) => { const q = new URL(req.url, REDIRECT_URI).searchParams; res.end("Authorized. You can close this window."); server.close(); if (q.get("state") !== state) throw new Error("state mismatch"); resolve(q.get("code")); }).listen(8085);});3. Exchange the code for an MCP JWT
Section titled “3. Exchange the code for an MCP JWT”Post the code to the facade’s token_endpoint, form-encoded. Send your API key so the
stored token is also tied to your gateway identity. Do not send the client secret: the
gateway adds it from the OAuth App Client record.
curl -s -X POST "$OAUTH/token" \ -H "X-API-Key: $API_KEY" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d grant_type=authorization_code \ -d code=na1-7c21-5e0b-4f4c-9a63-0d8e5b2f1c77 \ -d client_id=03012b66-5c17-4d7c-9297-39d9eb6c7c7f \ -d redirect_uri=http://localhost:8085/callback \ -d code_verifier=$VERIFIERAPI_KEY = "sk_brutor_api_3f9c..."
tok = httpx.post(token_url, headers={"X-API-Key": API_KEY}, data={ "grant_type": "authorization_code", "code": code, "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "code_verifier": verifier,})tok.raise_for_status()mcp_jwt = tok.json()["access_token"]const API_KEY = "sk_brutor_api_3f9c...";
const tok = await fetch(tokenUrl, { method: "POST", headers: { "X-API-Key": API_KEY }, body: new URLSearchParams({ grant_type: "authorization_code", code, client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, code_verifier: verifier, }),});if (!tok.ok) throw new Error(await tok.text());const mcpJwt = (await tok.json()).access_token;{ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "scope": "oauth crm.objects.contacts.read", "refresh_token": "de6e8e2a-4b9f-4a1c-8f0e-2c7d1b5a9e33", "user": { "user_id": "52731918", "username": "martin@example.com", "email": "martin@example.com", "name": null }, "token_info": { "type": "mcp_auth", "description": "Use this token for all requests to MCP server via the gateway", "oauth_stored": true, "auto_refresh": true }}| Field | Meaning |
|---|---|
access_token |
The MCP JWT — gateway-minted, not the provider’s token |
expires_in |
MCP JWT lifetime, JWT_EXPIRES_IN (default 3600) |
scope |
Scopes the provider granted (empty string if it returned none) |
refresh_token |
The refresh token the provider returned, echoed as issued (null if none) |
user |
The user as read from the IdP’s userinfo endpoint |
token_info.oauth_stored |
The provider’s tokens are stored encrypted in the gateway |
token_info.auto_refresh |
A provider refresh token is stored, so the gateway renews the access token itself |
4. Call the MCP server
Section titled “4. Call the MCP server”Send both credentials: your API key in X-API-Key authenticates you and selects your
resource group; the MCP JWT in Authorization selects the stored upstream token.
curl -s -X POST "$GW/v1/proxy/mcp/mcp-system-hubspot-default" \ -H "X-API-Key: $API_KEY" \ -H "Authorization: Bearer $MCP_JWT" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'from mcp import ClientSessionfrom mcp.client.streamable_http import streamablehttp_client
headers = {"X-API-Key": API_KEY, "Authorization": f"Bearer {mcp_jwt}"}async with streamablehttp_client(f"{GW}/v1/proxy/mcp/mcp-system-hubspot-default", headers=headers) as (r, w, _): async with ClientSession(r, w) as session: await session.initialize() tools = await session.list_tools()import { Client } from "@modelcontextprotocol/sdk/client/index.js";import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const transport = new StreamableHTTPClientTransport( new URL(`${GW}/v1/proxy/mcp/mcp-system-hubspot-default`), { requestInit: { headers: { "X-API-Key": API_KEY, Authorization: `Bearer ${mcpJwt}` } } },);const client = new Client({ name: "my-agent", version: "1.0.0" });await client.connect(transport);const tools = await client.listTools();The gateway strips both headers, checks your resource group’s access to the server,
decrypts the stored HubSpot token (refreshing it if needed) and forwards
Authorization: Bearer <HubSpot token> upstream. The response is the upstream server’s
ordinary JSON-RPC result.
5. Refresh the MCP JWT
Section titled “5. Refresh the MCP JWT”When the MCP JWT expires, get a new one without asking the user again: post the old MCP JWT
(expired is fine) as refresh_token to the same server’s token endpoint. The gateway
renews the stored provider token first if it has expired.
curl -s -X POST "$OAUTH/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d grant_type=refresh_token \ -d refresh_token=$MCP_JWTmcp_jwt = httpx.post(token_url, data={ "grant_type": "refresh_token", "refresh_token": mcp_jwt,}).json()["access_token"]const refreshed = await fetch(tokenUrl, { method: "POST", body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: mcpJwt }),});mcpJwt = (await refreshed.json()).access_token;{ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "token_info": { "type": "mcp_auth", "description": "Refreshed MCP JWT", "oauth_stored": true, "auto_refresh": true }}An MCP JWT for another server is refused with 400 Token mcp_server_id '...' does not match URL path '...'. If the stored token is gone, revoked, or expired with no provider refresh
token, the refresh fails and the user must authorize again.
6. List the stored tokens
Section titled “6. List the stored tokens”Returns every stored token record for the user across all MCP servers in the tenant,
whichever server is in the path. Requires a gateway credential; the user is taken from the
MCP JWT in Authorization, falling back to the gateway user.
curl -s "$OAUTH/tokens" \ -H "X-API-Key: $API_KEY" \ -H "Authorization: Bearer $MCP_JWT"{ "user_id": "52731918", "tenant_id": "default", "tokens": [ { "mcp_server_id": "mcp-system-hubspot-default", "tenant_id": "default", "idp_id": "idp-system-hubspot-default", "token_type": "bearer", "expires_at": "2026-10-28T17:40:12.483120+00:00", "is_expired": false, "scopes": ["oauth", "crm.objects.contacts.read"], "has_refresh_token": true, "created_at": "2026-10-28T16:40:12.483120+00:00", "last_refreshed_at": null, "refresh_count": 0, "revoked": false } ]}No secret ever appears. Without a gateway credential the endpoint returns 401 Authentication required.
7. Disconnect
Section titled “7. Disconnect”Revoke the user’s stored token for this MCP server when they disconnect the tool. Send the
MCP JWT in Authorization (or as a token form field); expired MCP JWTs are accepted.
curl -s -X POST "$OAUTH/revoke" -H "Authorization: Bearer $MCP_JWT"{"revoked": true}404 No active token found to revoke if there was nothing to revoke. This marks the row
revoked in the gateway only: it does not call the provider’s revocation endpoint and does
not invalidate the MCP JWT itself, which simply stops unlocking anything (MCP calls with it
return 401 oauth_reauth_required). To also revoke at the provider, an admin revokes the
token from OAuth Tokens.

