{"id":10323,"date":"2026-08-26T04:46:24","date_gmt":"2026-08-26T11:46:24","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/"},"modified":"2026-08-26T04:46:24","modified_gmt":"2026-08-26T11:46:24","slug":"mcp-server-oauth-keycloak-m2m-setup","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/","title":{"rendered":"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/tree\/main\/mcp_auth_keycloak_m2m\/mcp_auth_keycloak_m2m.ipynb\">View Source<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this flow, a client authenticates using a client ID and secret with no user login \u2014 ideal for automated agents, scripts, and server-to-server access.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\u2139\ufe0f <strong>What is M2M?<\/strong> Machine-to-Machine (M2M) authentication uses the <a href=\"https:\/\/datatracker.ietf.org\/doc\/html\/rfc6749#section-4.4\">OAuth 2.0 Client Credentials Grant<\/a> \u2014 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.<\/p>\n<\/blockquote>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\ud83d\udcd6 You can read more about <a href=\"https:\/\/mcp-server.couchbase.com\/configuration\/oauth\">Couchbase MCP Server OAuth Authentication<\/a> and the <a href=\"https:\/\/www.keycloak.org\/documentation\">Keycloak documentation<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<h3 id=\"h-prerequisites\" class=\"wp-block-heading\">Prerequisites<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keycloak<\/li>\n\n\n<li>(optional) MCP Inspector or any IDE (if IDE verification is needed)<\/li>\n\n\n<li>A running Couchbase cluster with credentials<\/li>\n\n\n<li><code>jq<\/code> installed for parsing JSON responses<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-what-to-expect\" class=\"wp-block-heading\">What to expect<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial is organized into two steps:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Step 1 \u2014 Keycloak and MCP server setup (foundation for the M2M flow)<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This step sets up the identity provider configuration and the MCP server so that machine clients can authenticate without any user interaction.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Set up a dedicated Keycloak realm to isolate MCP configuration from other applications<\/li>\n\n\n<li>Create custom OAuth scopes (<code>couchbase-mcp:read<\/code> and <code>couchbase-mcp:write<\/code>) that the MCP server uses for per-tool access enforcement<\/li>\n\n\n<li>Register the Couchbase MCP server as a resource server in Keycloak, defining the audience and scope contract for issued tokens<\/li>\n\n\n<li>Register a confidential M2M client with the client credentials grant enabled \u2014 this is the identity the agent or script presents to Keycloak to obtain tokens<\/li>\n\n\n<li>Start the MCP server with OAuth token verification enabled (no PRM needed for M2M)<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Step 2 \u2014 M2M flow (headless, no browser, no user)<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This step demonstrates two ways a machine client can connect to the MCP server using tokens fetched automatically from Keycloak.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Fetch a token using the client credentials grant (client ID + secret only, no user login)<\/li>\n\n\n<li>Validate the connection using MCP Inspector with a manually pasted static Bearer token<\/li>\n\n\n<li>Run a headless LangChain agent that fetches its own token automatically, connects to the MCP server over HTTP, and calls Couchbase tools \u2014 no IDE, no browser, no user interaction required<\/li>\n\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 id=\"h-prerequisite\" class=\"wp-block-heading\">Prerequisite<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For this tutorial, Keycloak is run locally to demonstrate the tutorial using docker, by running the following:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker run -p 8080:8080 \n  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \n  -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \n  quay.io\/keycloak\/keycloak:latest start-dev\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Open <a href=\"http:\/\/localhost:8080\">http:\/\/localhost:8080<\/a> and log in with <code>admin<\/code> \/ <code>admin<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keycloak might already be running in your case.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_1.png?raw=true\"\/><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 id=\"h-step-1-keycloak-setup\" class=\"wp-block-heading\">Step 1 \u2014 Keycloak Setup<\/h3>\n\n\n\n<h4 id=\"h-step-1-1-create-a-realm\" class=\"wp-block-heading\">Step 1.1 \u2014 Create a Realm<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A Realm in Keycloak is an isolated security domain \u2014 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. <a href=\"https:\/\/www.keycloak.org\/docs\/latest\/server_admin\/#core-concepts-and-terms\">See Keycloak Realm concepts<\/a> for more.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Steps:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Click the top-left dropdown \u2192 <strong>Create Realm<\/strong><\/li>\n\n\n<li>Name it <code>mcp-realm<\/code> \u2192 <strong>Create<\/strong><\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_2.png?raw=true\"\/><\/figure>\n\n\n\n<h4 id=\"h-step-1-2-create-custom-scopes\" class=\"wp-block-heading\">Step 1.2 \u2014 Create custom scopes<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Client Scopes in Keycloak define the permissions that can appear in an access token&#8217;s scope claim. The Couchbase MCP server uses two scopes to enforce per-tool access control \u2014 <code>couchbase-mcp:read<\/code> for read-only tools and <code>couchbase-mcp:write<\/code> for mutation tools. See <a href=\"https:\/\/www.keycloak.org\/docs\/latest\/server_admin\/#_client_scopes\">Keycloak Client Scopes documentation<\/a> for more.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Steps:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Left nav \u2192 <strong>Client Scopes<\/strong> \u2192 <strong>Create client scope<\/strong><\/li>\n\n\n<li>Create <code>couchbase-mcp:read<\/code>:\n<ul>\n<li>Name: <code>couchbase-mcp:read<\/code><\/li>\n<li>Type: <code>Optional<\/code><\/li>\n<li>Protocol: <code>openid-connect<\/code><\/li>\n<li><strong>Include in token scope<\/strong> \u2192 toggle <strong>On<\/strong> \u2014 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.<\/li>\n<li><strong>Save<\/strong><\/li>\n<\/ul>\n<\/li>\n\n\n<li>Repeat for <code>couchbase-mcp:write<\/code><\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_3.png?raw=true\"\/><\/figure>\n\n\n\n<h4 id=\"h-step-1-3-register-couchbase-mcp-server-as-a-resource-server-in-keycloak\" class=\"wp-block-heading\">Step 1.3 \u2014 Register Couchbase MCP Server as a Resource Server in Keycloak<\/h4>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\u2139\ufe0f <strong>Keycloak&#8217;s &#8220;Client&#8221; terminology:<\/strong> In Keycloak, everything is called a &#8220;Client&#8221; \u2014 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 \u2014 i.e. the Couchbase MCP server itself. Its purpose is to define the audience (<code>aud<\/code> claim) and the scopes that tokens must carry to access it. This is different from the OAuth client you&#8217;ll create in Step 2.1, which represents the application (agent or inspector) that actually requests tokens. See <a href=\"https:\/\/www.keycloak.org\/docs\/latest\/server_admin\/#_clients\">Keycloak Client concepts<\/a> for more.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">This represents the resource server (the audience).<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Left nav \u2192 <strong>Clients<\/strong> \u2192 <strong>Create client<\/strong><\/li>\n\n\n<li>Client ID: <code>couchbase-mcp-server<\/code><\/li>\n\n\n<li>Client authentication: <strong>Off<\/strong> (public)<\/li>\n\n\n<li>Click through to <strong>Save<\/strong><\/li>\n\n\n<li>Go to <strong>Client Scopes<\/strong> tab \u2192 <strong>Add client scope<\/strong> \u2192 add both <code>couchbase-mcp:read<\/code> and <code>couchbase-mcp:write<\/code> as <strong>Optional<\/strong><\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_4.png?raw=true\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_5.png?raw=true\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_6.png?raw=true\"\/><\/figure>\n\n\n\n<h4 id=\"h-step-1-4-add-audience-mapper\" class=\"wp-block-heading\">Step 1.4 \u2014 Add audience mapper<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase verifies the <code>aud<\/code> claim and is mandatory for Authentication. By default, Keycloak does not include the resource server&#8217;s client ID in the token&#8217;s <code>aud<\/code> (audience) claim. The MCP server validates the <code>aud<\/code> claim to ensure the token was issued specifically for it \u2014 without this mapper, every token will be rejected with an audience mismatch error. See <a href=\"https:\/\/www.keycloak.org\/docs\/latest\/server_admin\/#audience-support\">Keycloak Audience Support<\/a> for more.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Follow these steps to ensure Keycloak issued JWT token contains the <code>aud<\/code> claim.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go to <strong>Client Scopes<\/strong> \u2192 <code>couchbase-mcp:read<\/code> \u2192 <strong>Mappers<\/strong> tab \u2192 <strong>Add mapper<\/strong> \u2192 <strong>By configuration<\/strong> \u2192 <strong>Audience<\/strong><\/li>\n\n\n<li>Fill in:\n<ul>\n<li>Name: <code>couchbase-mcp-audience<\/code><\/li>\n<li>Included Client Audience: <code>couchbase-mcp-server<\/code><\/li>\n<li>Add to access token: <strong>On<\/strong><\/li>\n<li><strong>Save<\/strong><\/li>\n<\/ul>\n<\/li>\n\n\n<li>Repeat on <code>couchbase-mcp:write<\/code> scope (or add the mapper once to a shared scope)<\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_10.png?raw=true\"\/><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 id=\"h-step-2-m2m-flow\" class=\"wp-block-heading\">Step 2 \u2014 M2M Flow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h4 id=\"h-step-2-1-create-a-confidential-m2m-client\" class=\"wp-block-heading\">Step 2.1 \u2014 Create a confidential M2M client<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This creates the OAuth client \u2014 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 <a href=\"https:\/\/www.keycloak.org\/docs\/latest\/server_admin\/#_client-credentials\">Client Credentials Grant<\/a>. It needs to be confidential (client authentication On) so it can hold a secret safely.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Steps:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Left nav \u2192 <strong>Clients<\/strong> \u2192 <strong>Create client<\/strong><\/li>\n\n\n<li>Client ID: <code>mcp-static-client<\/code><\/li>\n\n\n<li>Client authentication: <strong>On<\/strong> (confidential) \u2014 important: the Credentials tab only appears after Client authentication is enabled<\/li>\n\n\n<li>Authorization: <strong>Off<\/strong> \u2014 this is Keycloak&#8217;s fine-grained authorization service, not needed here since the MCP server handles its own scope enforcement<\/li>\n\n\n<li>Authentication flow: check <strong>Service accounts roles<\/strong> \u2014 this enables the client credentials grant. Do not check Direct access grants (that&#8217;s for password grant with a user)<\/li>\n\n\n<li><strong>Save<\/strong><\/li>\n\n\n<li>Go to <strong>Credentials<\/strong> tab \u2192 copy the <strong>Client Secret<\/strong><\/li>\n\n\n<li><strong>Client Scopes<\/strong> tab \u2192 add <code>couchbase-mcp:read<\/code> and <code>couchbase-mcp:write<\/code> as <strong>Optional<\/strong><\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_8.png?raw=true\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_9.png?raw=true\"\/><\/figure>\n\n\n\n<h4 id=\"h-step-2-2-get-a-static-token\" class=\"wp-block-heading\">Step 2.2 \u2014 Get a static token<\/h4>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>export TOKEN=$(curl -s -X POST \n  http:\/\/localhost:8080\/realms\/mcp-realm\/protocol\/openid-connect\/token \n  -H &quot;Content-Type: application\/x-www-form-urlencoded&quot; \n  --data-urlencode &quot;grant_type=client_credentials&quot; \n  --data-urlencode &quot;client_id=mcp-static-client&quot; \n  --data-urlencode &quot;client_secret=&lt;YOUR_CLIENT_SECRET&gt;&quot; | jq -r .access_token)\n\necho &quot;$TOKEN&quot;\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-verify-the-token-at-jwt-io-confirm\" class=\"wp-block-heading\">Verify the token at jwt.io \u2014 confirm:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">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 \u2014 iss (who issued it), aud (who it&#8217;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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Paste the token value at jwt.io to decode and inspect the claims. Confirm:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>iss<\/code> = <code>http:\/\/localhost:8080\/realms\/mcp-realm<\/code><\/li>\n\n\n<li><code>aud<\/code> contains <code>couchbase-mcp-server<\/code><\/li>\n\n\n<li><code>scope<\/code> contains <code>couchbase-mcp:read couchbase-mcp:write<\/code><\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">\u26a0\ufe0f 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 \u2014 e.g. python3 -c &#8220;import sys,base64,json; p=sys.argv[1].split(&#8216;.&#8217;)[1]; p+=&#8217;=&#8217;*(-len(p)%4); print(json.dumps(json.loads(base64.urlsafe_b64decode(p)),indent=2))&#8221; &#8220;$TOKEN&#8221;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_12.png?raw=true\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>uvx couchbase-mcp-server \n  --transport=http \n  --connection-string=&quot;couchbase:\/\/127.0.0.1&quot; \n  --username=&quot;Administrator&quot; \n  --password=&quot;&lt;your-couchbase-password&gt;&quot; \n  --read-only-mode=false \n  --oauth-jwks-uri=&quot;http:\/\/localhost:8080\/realms\/mcp-realm\/protocol\/openid-connect\/certs&quot; \n  --oauth-issuer=&quot;http:\/\/localhost:8080\/realms\/mcp-realm&quot; \n  --oauth-audience=&quot;couchbase-mcp-server&quot;\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Note: no <code>--oauth-mcp-base-url<\/code> \u2014 pure token verification mode, no PRM endpoint needed for M2M.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Verify the gate rejects unauthenticated calls:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>curl -i -X POST http:\/\/127.0.0.1:8000\/mcp \n  -H &quot;Content-Type: application\/json&quot; \n  -d &#039;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;method&quot;:&quot;tools\/list&quot;}&#039;\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Expect a <code>401<\/code> response \u2014 confirms the OAuth gate is active.<\/p>\n\n\n\n<h4 id=\"h-step-2-4-run-as-a-headless-langchain-agent\" class=\"wp-block-heading\">Step 2.4 \u2014 Run as a headless LangChain agent<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This is the production M2M pattern \u2014 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The existing <a href=\"https:\/\/developer.couchbase.com\/tutorial-ai-agent-using-langchain-and-couchbase-mcp-server\/\">LangChain + Couchbase MCP tutorial<\/a> uses stdio transport without auth. This section adapts it to use HTTP transport with OAuth M2M.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Install dependencies<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Using uv (recommended)\nmkdir mcp-agent-keycloak &amp;&amp; cd mcp-agent-keycloak\nuv init\nuv add langchain langgraph langchain-openai langchain-mcp-adapters httpx-auth python-dotenv\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Set up environment variables<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create a <code>.env<\/code> file:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>OPENAI_API_KEY=&lt;your-openai-api-key&gt;\n\n# Keycloak M2M credentials\nKEYCLOAK_BASE_URL=http:\/\/localhost:8080\nKEYCLOAK_REALM=mcp-realm\nKEYCLOAK_CLIENT_ID=mcp-static-client\nKEYCLOAK_CLIENT_SECRET=&lt;your-client-secret&gt;\nKEYCLOAK_SCOPE=couchbase-mcp:read couchbase-mcp:write\n\n# MCP server\nMCP_SERVER_URL=http:\/\/127.0.0.1:8000\/mcp\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Agent code<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Save as <code>agent.py<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import os\nimport asyncio\nfrom dotenv import load_dotenv\nfrom httpx_auth import OAuth2ClientCredentials\nfrom langchain_openai import ChatOpenAI\nfrom langchain_mcp_adapters.client import MultiServerMCPClient\nfrom langgraph.prebuilt import create_react_agent\n\nload_dotenv()\n\n# Handles the full client_credentials dance: mints on first use, caches,\n# and auto-refreshes before expiry \u2014 no manual token code needed.\nkeycloak_auth = OAuth2ClientCredentials(\n    token_url=f&quot;{os.environ[&#039;KEYCLOAK_BASE_URL&#039;]}\/realms\/{os.environ[&#039;KEYCLOAK_REALM&#039;]}\/protocol\/openid-connect\/token&quot;,\n    client_id=os.environ[&quot;KEYCLOAK_CLIENT_ID&quot;],\n    client_secret=os.environ[&quot;KEYCLOAK_CLIENT_SECRET&quot;],\n    scope=os.environ.get(&quot;KEYCLOAK_SCOPE&quot;, &quot;couchbase-mcp:read couchbase-mcp:write&quot;),\n)\n\n\nasync def run_agent(query: str):\n    client = MultiServerMCPClient(\n        {\n            &quot;couchbase&quot;: {\n                &quot;url&quot;: os.environ[&quot;MCP_SERVER_URL&quot;],\n                &quot;transport&quot;: &quot;streamable_http&quot;,\n                &quot;auth&quot;: keycloak_auth,\n                &quot;headers&quot;: {&quot;Accept&quot;: &quot;application\/json, text\/event-stream&quot;},\n            }\n        }\n    )\n    tools = await client.get_tools()\n\n    llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)\n    agent = create_react_agent(llm, tools)\n\n    result = await agent.ainvoke(\n        {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}]}\n    )\n    return result[&quot;messages&quot;][-1].content\n\n\nif __name__ == &quot;__main__&quot;:\n    answer = asyncio.run(\n        run_agent(&quot;List all buckets in the Couchbase cluster&quot;)\n    )\n    print(answer)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Run it<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Make sure the MCP server is running (Step 2.3), then:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>uv run agent.py\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The agent will:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>OAuth2ClientCredentials<\/code> automatically fetches a token from Keycloak on first use<\/li>\n\n\n<li>Caches the token and auto-refreshes before expiry \u2014 no manual token management needed<\/li>\n\n\n<li>Connect to the MCP server over HTTP with the JWT in the Authorization header<\/li>\n\n\n<li>Discover the Couchbase tools<\/li>\n\n\n<li>Answer the query using LangChain&#8217;s ReAct loop<\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_14.png?raw=true\"\/><\/figure>\n\n\n\n<h4 id=\"h-optional-step-2-5-test-in-mcp-inspector\" class=\"wp-block-heading\">(Optional) Step 2.5 \u2014 Test in MCP Inspector<\/h4>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>npx @modelcontextprotocol\/inspector\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the Inspector UI:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Transport Type: <code>Streamable HTTP<\/code><\/li>\n\n\n<li>URL: <code>http:\/\/127.0.0.1:8000\/mcp<\/code><\/li>\n\n\n<li>Under Authentication \u2192 Custom Headers \u2192 add:\n<ul>\n<li>Header name: <code>Authorization<\/code><\/li>\n<li>Header value: <code>Bearer &lt;paste $TOKEN value&gt;<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n<li>Click <strong>Connect<\/strong><\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Verify:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Tools<\/strong> tab \u2192 <strong>List Tools<\/strong> \u2014 should show all 24 Couchbase MCP tools<\/li>\n\n\n<li>Run a read tool (e.g. <code>get_server_status<\/code>) \u2192 success<\/li>\n\n\n<li>Run a write tool (e.g. <code>upsert_document_by_id<\/code>) \u2192 success (token has both scopes)<\/li>\n\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_13.png?raw=true\"\/><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\u2139\ufe0f <strong>Token expiry:<\/strong> Keycloak access tokens expire in 5 minutes by default (configurable in Realm Settings \u2192 Tokens).<\/p>\n<\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>View Source 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 \u2014 [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"inline_featured_image":false,"_acf":"","footnotes":""},"tutorial-languages":[606],"tutorial-tags":[630],"tutorial-technologies":[631],"tutorial-types":[555],"class_list":["post-10323","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-python","tutorial-tags-model-context-protocol-mcp","tutorial-technologies-model-context-protocol-mcp","tutorial-types-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.8 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/\" \/>\n<meta property=\"og:locale\" content=\"de_DE\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow\" \/>\n<meta property=\"og:description\" content=\"View Source 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 \u2014 [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_1.png?raw=true\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"9\u00a0Minuten\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/\",\"name\":\"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/github.com\\\/couchbase-examples\\\/mcp-cookbook\\\/blob\\\/main\\\/mcp_auth_keycloak_m2m\\\/keycloak_screenshots\\\/key_1.png?raw=true\",\"datePublished\":\"2026-08-26T11:46:24+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/#breadcrumb\"},\"inLanguage\":\"de\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"de\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/#primaryimage\",\"url\":\"https:\\\/\\\/github.com\\\/couchbase-examples\\\/mcp-cookbook\\\/blob\\\/main\\\/mcp_auth_keycloak_m2m\\\/keycloak_screenshots\\\/key_1.png?raw=true\",\"contentUrl\":\"https:\\\/\\\/github.com\\\/couchbase-examples\\\/mcp-cookbook\\\/blob\\\/main\\\/mcp_auth_keycloak_m2m\\\/keycloak_screenshots\\\/key_1.png?raw=true\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/mcp-server-oauth-keycloak-m2m-setup\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/ko\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"de\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"de\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/","og_locale":"de_DE","og_type":"article","og_title":"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow","og_description":"View Source 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 \u2014 [&hellip;]","og_url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"url":"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_1.png?raw=true","type":"","width":"","height":""}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"9\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/","url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/","name":"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/de\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/#primaryimage"},"image":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/#primaryimage"},"thumbnailUrl":"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_1.png?raw=true","datePublished":"2026-08-26T11:46:24+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/"]}]},{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/#primaryimage","url":"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_1.png?raw=true","contentUrl":"https:\/\/github.com\/couchbase-examples\/mcp-cookbook\/blob\/main\/mcp_auth_keycloak_m2m\/keycloak_screenshots\/key_1.png?raw=true"},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/mcp-server-oauth-keycloak-m2m-setup\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/ko\/"},{"@type":"ListItem","position":2,"name":"Securing Couchbase MCP Server with Keycloak \u2014 Machine-to-Machine (M2M) Flow"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/de\/#website","url":"https:\/\/www.couchbase.com\/de\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/de\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/de\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"de"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/de\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/de\/","logo":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase ist ein in San Jose, Kalifornien, ans\u00e4ssiges Unternehmen f\u00fcr Datenbanksoftware, das eine operative Datenplattform f\u00fcr KI bereitstellt, die von Hunderten von globalen Unternehmen eingesetzt wird.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10323","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10323\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/media?parent=10323"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-languages?post=10323"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-tags?post=10323"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-technologies?post=10323"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-types?post=10323"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}