- Learn how to run the Couchbase MCP server in Streamable HTTP mode with OAuth so it can serve machine-to-machine clients authenticated by Keycloak.
- This tutorial walks through configuring Keycloak, and obtaining a JWT with the OAuth 2.0 client credentials grant.
- You will verify the token claims and run a headless LangChain agent that fetches and refreshes its own token with no user login.
This tutorial showcases how to set-up the Couchbase MCP server in Streamable HTTP mode with OAuth settings so that it serves clients that operate in the Machine-to-Machine flow (client credentials grants) using the IDP/Authorization server Keycloak.
In this flow, a client authenticates using a client ID and secret with no user login — ideal for automated agents, scripts, and server-to-server access.
ℹ️ What is M2M? Machine-to-Machine (M2M) authentication uses the OAuth 2.0 Client Credentials Grant — an application authenticates directly using its own credentials (client ID + secret) rather than on behalf of a user. This is the standard pattern for headless agents, background services, and server-to-server API calls.
📖 You can read more about Couchbase MCP Server OAuth Authentication and the Keycloak documentation.
Prerequisites
- Keycloak
- (optional) MCP Inspector or any IDE (if IDE verification is needed)
- A running Couchbase cluster with credentials
jqinstalled for parsing JSON responses
What to expect
This tutorial is organized into two steps:
Step 1 — Keycloak and MCP server setup (foundation for the M2M flow)
This step sets up the identity provider configuration and the MCP server so that machine clients can authenticate without any user interaction.
- Set up a dedicated Keycloak realm to isolate MCP configuration from other applications
- Create custom OAuth scopes (
couchbase-mcp:readandcouchbase-mcp:write) that the MCP server uses for per-tool access enforcement - Register the Couchbase MCP server as a resource server in Keycloak, defining the audience and scope contract for issued tokens
- Register a confidential M2M client with the client credentials grant enabled — this is the identity the agent or script presents to Keycloak to obtain tokens
- Start the MCP server with OAuth token verification enabled (no PRM needed for M2M)
Step 2 — M2M flow (headless, no browser, no user)
This step demonstrates two ways a machine client can connect to the MCP server using tokens fetched automatically from Keycloak.
- Fetch a token using the client credentials grant (client ID + secret only, no user login)
- Validate the connection using MCP Inspector with a manually pasted static Bearer token
- Run a headless LangChain agent that fetches its own token automatically, connects to the MCP server over HTTP, and calls Couchbase tools — no IDE, no browser, no user interaction required
Prerequisite
For this tutorial, Keycloak is run locally to demonstrate the tutorial using docker, by running the following:
docker run -p 8080:8080
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin
-e KC_BOOTSTRAP_ADMIN_PASSWORD=admin
quay.io/keycloak/keycloak:latest start-dev
Open http://localhost:8080 and log in with admin / admin.
Keycloak might already be running in your case.

Step 1 — Keycloak Setup
Step 1.1 — Create a Realm
A Realm in Keycloak is an isolated security domain — it has its own set of users, clients, scopes, and configurations. Think of it as a tenant. Creating a dedicated realm for MCP keeps your MCP configuration cleanly separated from any other applications in your Keycloak instance. See Keycloak Realm concepts for more.
Steps:
- Click the top-left dropdown → Create Realm
- Name it
mcp-realm→ Create

Step 1.2 — Create custom scopes
Client Scopes in Keycloak define the permissions that can appear in an access token’s scope claim. The Couchbase MCP server uses two scopes to enforce per-tool access control — couchbase-mcp:read for read-only tools and couchbase-mcp:write for mutation tools. See Keycloak Client Scopes documentation for more.
Steps:
- Left nav → Client Scopes → Create client scope
- Create
couchbase-mcp:read:- Name:
couchbase-mcp:read - Type:
Optional - Protocol:
openid-connect - Include in token scope → toggle On — this makes the scope name appear in the scope claim of the token. Without this, the scope is assigned but never shows up in the token even if the client requests it.
- Save
- Name:
- Repeat for
couchbase-mcp:write

Step 1.3 — Register Couchbase MCP Server as a Resource Server in Keycloak
ℹ️ Keycloak’s “Client” terminology: In Keycloak, everything is called a “Client” — both the application requesting tokens (the OAuth client) and the API being protected (the resource server). This step creates a Keycloak Client that represents the resource server — i.e. the Couchbase MCP server itself. Its purpose is to define the audience (
audclaim) and the scopes that tokens must carry to access it. This is different from the OAuth client you’ll create in Step 2.1, which represents the application (agent or inspector) that actually requests tokens. See Keycloak Client concepts for more.
This represents the resource server (the audience).
- Left nav → Clients → Create client
- Client ID:
couchbase-mcp-server - Client authentication: Off (public)
- Click through to Save
- Go to Client Scopes tab → Add client scope → add both
couchbase-mcp:readandcouchbase-mcp:writeas Optional



Step 1.4 — Add audience mapper
Couchbase verifies the aud claim and is mandatory for Authentication. By default, Keycloak does not include the resource server’s client ID in the token’s aud (audience) claim. The MCP server validates the aud claim to ensure the token was issued specifically for it — without this mapper, every token will be rejected with an audience mismatch error. See Keycloak Audience Support for more.
Follow these steps to ensure Keycloak issued JWT token contains the aud claim.
- Go to Client Scopes →
couchbase-mcp:read→ Mappers tab → Add mapper → By configuration → Audience - Fill in:
- Name:
couchbase-mcp-audience - Included Client Audience:
couchbase-mcp-server - Add to access token: On
- Save
- Name:
- Repeat on
couchbase-mcp:writescope (or add the mapper once to a shared scope)

Step 2 — M2M Flow
This flow uses the client credentials grant to get a token, then passes it as a Bearer token to the MCP server. Tested with MCP Inspector and a headless LangChain agent.
Step 2.1 — Create a confidential M2M client
This creates the OAuth client — the application (agent or script) that will request tokens from Keycloak. Unlike the resource server client in Step 1.3, this client actively authenticates to Keycloak using a client secret and requests access tokens via the Client Credentials Grant. It needs to be confidential (client authentication On) so it can hold a secret safely.
Steps:
- Left nav → Clients → Create client
- Client ID:
mcp-static-client - Client authentication: On (confidential) — important: the Credentials tab only appears after Client authentication is enabled
- Authorization: Off — this is Keycloak’s fine-grained authorization service, not needed here since the MCP server handles its own scope enforcement
- Authentication flow: check Service accounts roles — this enables the client credentials grant. Do not check Direct access grants (that’s for password grant with a user)
- Save
- Go to Credentials tab → copy the Client Secret
- Client Scopes tab → add
couchbase-mcp:readandcouchbase-mcp:writeas Optional


Step 2.2 — Get a static token
export TOKEN=$(curl -s -X POST
http://localhost:8080/realms/mcp-realm/protocol/openid-connect/token
-H "Content-Type: application/x-www-form-urlencoded"
--data-urlencode "grant_type=client_credentials"
--data-urlencode "client_id=mcp-static-client"
--data-urlencode "client_secret=<YOUR_CLIENT_SECRET>" | jq -r .access_token)
echo "$TOKEN"
Verify the token at jwt.io — confirm:
A JWT (JSON Web Token) is a Base64-encoded string with three parts separated by dots: a header, a payload (the claims), and a signature. Decoding it lets you inspect the claims — iss (who issued it), aud (who it’s for), scope (what permissions it grants), and exp (when it expires). This is useful to confirm the token is correctly configured before sending it to the MCP server.
Paste the token value at jwt.io to decode and inspect the claims. Confirm:
iss=http://localhost:8080/realms/mcp-realmaudcontainscouchbase-mcp-serverscopecontainscouchbase-mcp:read couchbase-mcp:write
⚠️ jwt.io is a third-party tool. Never paste production tokens or tokens containing sensitive data into external websites. For development/testing tokens this is acceptable, but for production use a local decoder instead — e.g. python3 -c “import sys,base64,json; p=sys.argv[1].split(‘.’)[1]; p+=’=’*(-len(p)%4); print(json.dumps(json.loads(base64.urlsafe_b64decode(p)),indent=2))” “$TOKEN”

uvx couchbase-mcp-server
--transport=http
--connection-string="couchbase://127.0.0.1"
--username="Administrator"
--password="<your-couchbase-password>"
--read-only-mode=false
--oauth-jwks-uri="http://localhost:8080/realms/mcp-realm/protocol/openid-connect/certs"
--oauth-issuer="http://localhost:8080/realms/mcp-realm"
--oauth-audience="couchbase-mcp-server"
Note: no --oauth-mcp-base-url — pure token verification mode, no PRM endpoint needed for M2M.
Verify the gate rejects unauthenticated calls:
curl -i -X POST http://127.0.0.1:8000/mcp
-H "Content-Type: application/json"
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
Expect a 401 response — confirms the OAuth gate is active.
Step 2.4 — Run as a headless LangChain agent
This is the production M2M pattern — a Python agent that fetches its own token and connects to the MCP server over HTTP with no user interaction, no browser, and no IDE.
The existing LangChain + Couchbase MCP tutorial uses stdio transport without auth. This section adapts it to use HTTP transport with OAuth M2M.
Install dependencies
# Using uv (recommended)
mkdir mcp-agent-keycloak && cd mcp-agent-keycloak
uv init
uv add langchain langgraph langchain-openai langchain-mcp-adapters httpx-auth python-dotenv
Set up environment variables
Create a .env file:
OPENAI_API_KEY=<your-openai-api-key>
# Keycloak M2M credentials
KEYCLOAK_BASE_URL=http://localhost:8080
KEYCLOAK_REALM=mcp-realm
KEYCLOAK_CLIENT_ID=mcp-static-client
KEYCLOAK_CLIENT_SECRET=<your-client-secret>
KEYCLOAK_SCOPE=couchbase-mcp:read couchbase-mcp:write
# MCP server
MCP_SERVER_URL=http://127.0.0.1:8000/mcp
Agent code
Save as agent.py:
import os
import asyncio
from dotenv import load_dotenv
from httpx_auth import OAuth2ClientCredentials
from langchain_openai import ChatOpenAI
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
load_dotenv()
# Handles the full client_credentials dance: mints on first use, caches,
# and auto-refreshes before expiry — no manual token code needed.
keycloak_auth = OAuth2ClientCredentials(
token_url=f"{os.environ['KEYCLOAK_BASE_URL']}/realms/{os.environ['KEYCLOAK_REALM']}/protocol/openid-connect/token",
client_id=os.environ["KEYCLOAK_CLIENT_ID"],
client_secret=os.environ["KEYCLOAK_CLIENT_SECRET"],
scope=os.environ.get("KEYCLOAK_SCOPE", "couchbase-mcp:read couchbase-mcp:write"),
)
async def run_agent(query: str):
client = MultiServerMCPClient(
{
"couchbase": {
"url": os.environ["MCP_SERVER_URL"],
"transport": "streamable_http",
"auth": keycloak_auth,
"headers": {"Accept": "application/json, text/event-stream"},
}
}
)
tools = await client.get_tools()
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = create_react_agent(llm, tools)
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": query}]}
)
return result["messages"][-1].content
if __name__ == "__main__":
answer = asyncio.run(
run_agent("List all buckets in the Couchbase cluster")
)
print(answer)
Run it
Make sure the MCP server is running (Step 2.3), then:
uv run agent.py
The agent will:
OAuth2ClientCredentialsautomatically fetches a token from Keycloak on first use- Caches the token and auto-refreshes before expiry — no manual token management needed
- Connect to the MCP server over HTTP with the JWT in the Authorization header
- Discover the Couchbase tools
- Answer the query using LangChain’s ReAct loop

(Optional) Step 2.5 — Test in MCP Inspector
npx @modelcontextprotocol/inspector
In the Inspector UI:
- Transport Type:
Streamable HTTP - URL:
http://127.0.0.1:8000/mcp - Under Authentication → Custom Headers → add:
- Header name:
Authorization - Header value:
Bearer <paste $TOKEN value>
- Header name:
- Click Connect
Verify:
- Tools tab → List Tools — should show all 24 Couchbase MCP tools
- Run a read tool (e.g.
get_server_status) → success - Run a write tool (e.g.
upsert_document_by_id) → success (token has both scopes)

ℹ️ Token expiry: Keycloak access tokens expire in 5 minutes by default (configurable in Realm Settings → Tokens).