Blog

Who's asking? Per-user Elasticsearch access for Amazon Bedrock AgentCore agents

Every tool call runs as whoever is signed in, and revoking one user's access leaves everyone else working. Here's how to wire AgentCore Gateway to Elastic Cloud Serverless through an OAuth MCP client.

Agent Builder is available now GA. Get started with an Elastic Cloud Trial, and check out the documentation for Agent Builder here.

Most Amazon Bedrock AgentCore agents serve more than one person, and those people rarely have access to the same data. A support engineer needs customer tickets, while a contractor should only see the public docs. If your agent connects to Elasticsearch with a single API key, both of these users query as the same Elastic identity, and the agent could return data that the requester isn’t meant to see.

In this post, I connect AgentCore Gateway to an Elastic Cloud Serverless (Serverless) project through an OAuth Model Context Protocol (MCP) client instead. Each user signs in to Elastic once and authorizes the gateway. From then on, every tool call runs as the user who is signed in, with the roles that their account allows. I also cover how to revoke one user without rotating a key or impacting anyone else. OAuth MCP clients are available on Serverless.

The first call runs all nine steps shown in the following image. Every call after that runs four. Steps 4–7  are one-time sign-in and consent. After that, the user's JSON Web Token (JWT) goes to the gateway and their Elastic access token comes back, so the search runs as them.

You don't need a finished app or an AgentCore runtime to follow along. I share the scripts to run in place of the Return URL and AgentCore agent (Runtime) boxes shown below.

What you need before connecting AgentCore to Elasticsearch

  • An Elastic Cloud Serverless project. MCP clients that use OAuth are only available on Serverless projects.

  • Read access to Elastic Agent Builder in that project (required for creating the MCP client).

  • An AWS account with access to Amazon Bedrock AgentCore in a Region where it's available, plus permission to use AgentCore Identity, AgentCore Gateway, Amazon Cognito, and AWS Secrets Manager.

  • For the optional test scripts:

    • Python 3.13 or later.

    • curl.

    • jq.

    • Either mkcert or OpenSSL to create a local certificate.

Create an OAuth MCP client in Elastic Cloud Serverless

To let AgentCore talk to your project, you first need to create an OAuth MCP client. AgentCore uses this client to talk to the Agent Builder MCP server and to access the same MCP tools that your Agent Builder agent has. Find more details in the documentation here, or follow the steps below:

  1. Switch to the Kibana space whose agents and tools AgentCore should use. The client is tied to this space, and you can't change it later.

  2. Go to Agents → Tools → Manage all tools → Manage MCP → Manage MCP Clients (OAuth) → Add MCP client.

  3. Name your client (for example, AgentCore Gateway), and pick a logo.

  4. Select Remote under the Redirect URI type section.

  5. For now, fill in the Remote URL with any HTTPS URL, such as https://example.com. You’ll update it later.

  6. Check the Generate confidential MCP client box, and store the generated secret safely.

  7. Create a client.

Set up AgentCore Identity with your Elastic OAuth client

Next, set up the AWS resources that the gateway depends on. If you don’t have an application to test with yet, the optional helper scripts below let you complete the authorization step locally.

Create the AgentCore Identity OAuth client for Elastic

1. Store the client secret (from Step 6, above) in AWS Secrets Manager. For example:

2. In the Build tab, go to Amazon Bedrock AgentCore → Identity.

3. Create an Outbound Auth with an OAuth client:

4. Select Customized provider and Manual config.

5. Select Client secret post as your Client authentication method:

6. To get the correct values for Issuer, Authorization endpoint, and Token endpoint, open a terminal and run the following:

a. Get the OAuth authorization server used by your project:

export KIBANA_URL="..." 
# Leave SPACE_PATH empty if you created the client in the default space.
# For any other space, set it to /s/<space-id>, e.g. /s/marketing
export SPACE_PATH="..."
curl -s "$KIBANA_URL/.well-known/oauth-protected-resource$SPACE_PATH/api/agent_builder/mcp" | jq

Example response:

{
  "authorization_servers": [
    "https://oauth.iam.eu-west-1.aws.svc.elastic.cloud/oauth2"
  ],
  "resource": "https://<your-project>.kb.<region>.aws.elastic.cloud/api/agent_builder/mcp"
}

b. Take the authorization server URL from the response, and insert /.well-known/oauth-authorization-server after the host:

curl -s "https://oauth.iam.eu-west-1.aws.svc.elastic.cloud/.well-known/oauth-authorization-server/oauth2" | jq

Example response:

{
  "issuer": "https://oauth.iam.eu-west-1.aws.svc.elastic.cloud/oauth2",
  "authorization_endpoint": "https://oauth.iam.eu-west-1.aws.svc.elastic.cloud/oauth2/authorize",
  "token_endpoint": "https://oauth.iam.eu-west-1.aws.svc.elastic.cloud/oauth2/token",
  "response_types_supported": [
    "code"
  ],
  "grant_types_supported": [
    "authorization_code",
    "refresh_token"
  ],
  "code_challenge_methods_supported": [
    "plain",
    "S256"
  ],
  "token_endpoint_auth_methods_supported": [
    "none",
    "client_secret_post"
  ],
  "scopes_supported": [
    "all"
  ],
  "client_id_metadata_document_supported": false
}

7. Add code as the response type.

8. Copy the client ID from the AgentCore OAuth client that you created in the previous section, in your Serverless project:

9. Link the client secret from your Secrets Manager.

10. Create a client.

11. Now, as promised, let’s update the Remote URL of the client that we created in the Serverless project. Copy the Callback URL from your newly created identity, and paste it as the Remote URL in your Elastic OAuth MCP client:

Test locally without an app or AgentCore runtime (optional)

Run a local HTTPS callback server for the OAuth redirect

When creating a gateway target, you need to provide a Return URL. This is an endpoint in your app that the authorization page can redirect to, to complete the flow. AWS redirects here with a session ID. This endpoint must then call CompleteResourceTokenAuth, which checks that the user who started the session is the same user completing it. If you don’t already have this in your codebase, you can use this sample code to stand up a small local server on localhost:9090. The server runs over HTTPS because Elastic doesn't accept plain HTTP redirect URIs, and Chrome blocks the consent redirect from reaching http://localhost.

Before you run the server, make sure that you:

1. Export AWS credentials that can complete the authorization and look up your gateway targets. The server calls these AgentCore actions:

{
   "Version": "2012-10-17",
   "Statement": [
     {
       "Effect": "Allow",
       "Action": [
         "bedrock-agentcore:CompleteResourceTokenAuth",
         "bedrock-agentcore:ListGateways",
         "bedrock-agentcore:ListGatewayTargets",
         "bedrock-agentcore:GetGatewayTarget"
       ],
       "Resource": "*"
     }
   ]
}
# run this in AWS CloudShell and copy-paste the output into your terminal window
aws configure export-credentials --format env

2. Install the necessary dependencies:

python3 -m venv .venv
source .venv/bin/activate
pip install boto3 requests fastapi uvicorn bedrock-agentcore

3. Create self-signed certificates:

brew install mkcert
mkcert -install          # one-time: create and trust the local CA
mkdir -p certs
mkcert -cert-file certs/localhost.pem -key-file certs/localhost-key.pem localhost 127.0.0.1
# so that the test script trusts the certificate
export CALLBACK_CA_FILE="$(mkcert -CAROOT)/rootCA.pem"

Or via OpenSSL:

mkdir -p certs
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 365 \
  -keyout certs/localhost-key.pem \
  -out certs/localhost.pem \
  -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"

Click Advanced → Proceed to localhost when in Chrome.

Now run the server in your terminal window:

python oauth2_callback_server.py --region <your-aws-region>

Run the test script against your gateway

If you want to test the integration in a lightweight script, rather than directly in AWS, you can download this file and run it on your local machine:

# From the Cognito app client that AgentCore created for your gateway
export CLIENT_ID=...
export CLIENT_SECRET=...
# Get these from the Invocation Code on the Gateway page
export TOKEN_URL=...
export GATEWAY_URL=...
python gateway_elastic_test.py

Create an AgentCore Gateway with an MCP target

Finally, we’re ready to create the integration point on the AgentCore side. There are two target options:

  • A default, aggregated MCP target. On gateway creation, this caches the list of tools of the source MCP server and only refreshes it when explicitly synced or when the gateway is updated. Use this if your application triggers a sync regularly or based on events; otherwise, the cache has the potential to go stale.

  • A passthrough MCP target. This sends a tools/list request to the source MCP server every time, so a revoked or expired authorization shows up sooner.

Aggregated (default)

Passthrough

Tool list

Cached, refreshed when you sync the target

Fetched from Elastic on every tools/list

MCP URL

<gateway>/mcp

<gateway>/<target name>/mcp; remove /mcp from the MCP Endpoint

Where to send forceAuthentication

tools/call

tools/list

A revoked token shows up

On the next tool call

On the next tool list

1. Create an AgentCore Gateway with MCP version 2025-11-25 enabled. This spec version adds URL-mode elicitation and is the latest version that the Agent Builder MCP server currently supports. (Leave all other default options in place in steps 1 and 2.)

2. Select MCP target as target protocol and MCP server as target type.

3. (Optional) Select passthrough - advanced, if you don’t want a cache of available tools that you need to manually refresh.

4. Copy the MCP server URL from the Elastic OAuth MCP client in your Serverless project, and paste it under MCP Endpoint. Note: If you’re using a passthrough target, remove the /mcp suffix from the MCP server URL. AWS adds it by default.

5. Make sure that OAuth client is selected as Outbound Auth configuration and, in the dropdown, pick the AgentCore OAuth client that you created earlier.

6. Under Additional configurations, select Authorization code grant (3LO) under Auth grant type.

7.For Return URL, add your app’s endpoint where you complete the authorization with the session ID sent by AWS. If you don’t have this yet, use the server provided in the previous section: https://localhost:9090/oauth2/callback.

8. Add the all scope.

9. Create a gateway:

10. Close any notification pop-ups at the top of the page, after you read them. For example:

11. Authorize your target from the provided link, either from the notifications or from the Targets table:

12. You should see a page similar to this one:

13. If you used the local callback server for Return URL, you should see logs similar to the following:

14. After completing the authorization, your target should show up in Ready status:

Test per-user Elasticsearch permissions with Cognito users

By default, creating the gateway also creates a user pool in Amazon Cognito, an AWS service for user management and authorization/authentication. It holds the app client that your application uses to connect to the gateway, along with the users who can call the gateway directly.

1. Go to Amazon Cognito → User pools. Click on the auto-generated user pool. Open the Users page (under the User management tab), and add multiple users. You can think of each Cognito user as an Elastic user.

2. Update the app client. Go to Amazon Cognito → App clients. Click on the auto-generated app client. Then, turn on the Sign in with username and password: ALLOW_USER_PASSWORD_AUTH option.

3. Make your users’ passwords permanent by running the following in CloudShell:

aws cognito-idp admin-set-user-password --region eu-north-1 --user-pool-id <user-pool-id> --username alice --password <password> --permanent
aws cognito-idp admin-set-user-password --region eu-north-1 --user-pool-id <user-pool-id> --username bob --password <password> --permanent

4. Now run COGNITO_USERNAME=bob COGNITO_PASSWORD=<password> python gateway_elastic_test.py, and authorize as an Elastic user with a limited role.

For example, I used bob to log in as a separate, limited user, which I had attached to my Serverless project with a custom role. Here’s that role as returned by GET _security/role/limited_role:

{
  "limited_role": {
    "cluster": [],
    "indices": [
      {
        "names": [
          "visible-index-only-*"
        ],
        "privileges": [
          "read",
          "view_index_metadata"
        ],
        "field_security": {
          "grant": [
            "*"
          ],
          "except": []
        },
        "allow_restricted_indices": false
      }
    ],
    "applications": [
      {
        "application": "kibana-.kibana",
        "privileges": [
          "feature_agentBuilder.read"
        ],
        "resources": [
          "space:default"
        ]
      }
    ],
    "run_as": [],
    "metadata": {},
    "transient_metadata": {
      "enabled": true
    }
  }
}

The applications entry gives the role Read access to Agent Builder in the default space. If your MCP client lives in another space, change space:default to space:<your-space-id>.

To create a similar role from the Dev Tools console, send PUT _security/role/limited_role with the indices and applications sections as the request body. (See the create or update roles API.) You can also create the role in the UI.

When I call the test script as bob and authorize as the limited Elastic user, I see only the visible-index-only-test index, not dummy-data:

The gateway and tool remain the same, as does the OAuth MCP client. The only thing that changes is who's signed in: AgentCore Gateway calls your Agent Builder tools as that user, and Elastic returns what their role allows. The agent never has to know the difference.

You can also create multiple client credentials app clients in Cognito and add them to the gateway under Inbound Auth configurations. This is useful if, for example, you need multiple apps or agents to connect to your gateway.

How to revoke a user's Elasticsearch access through AgentCore

Revoking a user's connection to the OAuth MCP client removes their access through the agent, while their Elastic account and roles stay exactly as they are. For example, consider the contractor mentioned at the beginning of this post, who could only see a subset of what a permanent support engineer sees. Let's say that the contract wraps up and the contractor moves to a project in another part of the company. They'll still need Elasticsearch now and then, just not through the AgentCore agent anymore. Revoking their connection to the OAuth MCP client is all it takes, and everyone else using the agent carries on without noticing.

If you have the necessary admin permissions on your Serverless project, you can manage connections to your various OAuth clients and revoke them from the settings panel:

  1. Go to your Serverless project, Admin and settings → Application Connections.

  2. Select the client whose connections you want to revoke.

  3. Revoke all connections.

  4. (Optional) Alternatively, you can click on List View in the top-right corner and delete individual connections, rather than a whole grouping of them.

Revoking a connection takes effect immediately on the Elastic side. The next request that reaches your project with a revoked token is rejected, and you'll see responses like this:

AgentCore Gateway doesn't start a new authorization when this happens. It keeps sending the stored access token until that token expires, so your agent's tool calls fail during that window (up to one hour). Once the token expires, the gateway asks the user to authorize again, and the authorization link is in the WWW-Authenticate header or the response body:

If you want to immediately trigger a reauthorization instead of waiting for the token to expire, run the following:

FORCE_AUTHENTICATION=1 COGNITO_USERNAME=alice COGNITO_PASSWORD=<password> python gateway_elastic_test.py

This passes forceAuthentication: true in the request’s _meta . Under the hood, this ignores the old stored token and prompts for reauthorization. After you authorize, the script retries the request with the new token.

AgentCore calls the tools; Elasticsearch decides who sees what

We’ve completed the full chain. We saw how to set up an OAuth MCP client in Elastic and how to tie it to an AgentCore Identity. Plus, we saw how to use the two to connect an AgentCore Gateway to a Serverless project and query it over MCP.

Picture this setup a year from now: the support team has doubled, two contractors have come and gone, someone has moved from support over to finance. Yet your agent hasn't changed once. Everyone signs in to Elastic. They authorize the gateway and ask the same questions of the same tools, getting back only what their own role allows. When someone's job changes, you change their role. When they no longer need the agent, you revoke their connection.

Try it yourself, following the steps detailed above, and let us know your thoughts in our forums. For more information on how OAuth works for the Elasticsearch MCP server, see Elasticsearch MCP server OAuth authentication.

How helpful was this content?

Related Content

Why your agent forgets: The 5 jobs a memory system has to do before it’s worth building on

Why your agent forgets: The 5 jobs a memory system has to do before it’s worth building on

Maria Handoko
Query a million trades in natural language with AWS Quick and Elastic Agent Builder MCP server

Query a million trades in natural language with AWS Quick and Elastic Agent Builder MCP server

Udayasimha Theepireddy
Elasticsearch 9.6: Query Amazon S3 data in place, multiuser chat, and PDFs to Markdown

Elasticsearch 9.6: Query Amazon S3 data in place, multiuser chat, and PDFs to Markdown

Gregory Chase
Fine-grained authorization for Elasticsearch RAG with SpiceDB

Fine-grained authorization for Elasticsearch RAG with SpiceDB

Sohan Maheshwar
AI connectors in Kibana: 90+ data sources your agent can call

AI connectors in Kibana: 90+ data sources your agent can call

Erik Currin

Ready to build state of the art search experiences?

Sufficiently advanced search isn’t achieved with the efforts of one. Elasticsearch is powered by data scientists, ML ops, engineers, and many more who are just as passionate about search as you are. Let’s connect and work together to build the magical search experience that will get you the results you want.