
Connect web-search with Claude Code using Amazon Bedrock AgentCore Gateway
Give your AI coding assistants access to live web search — without distributing API keys. This post walks through adding the Web Search Tool to an AgentCore Gateway and connecting Claude Code, Claude Desktop, and Bedrock applications to it. You get centralized access control, zero data egress, and one MCP endpoint that every client discovers automatically.
When an AI coding assistant needs today's changelog, a pricing page that changed last week, or a GitHub issue opened an hour ago, it needs a web search tool — not just training data. But handing each client a raw search API key creates problems that compound as your team grows: credentials scattered across developer machines, no central visibility into who searched what, and no way to revoke access without touching every config file.
This post shows you how to give Claude Code, Claude Desktop (or Amazon Q Developer), and your own Bedrock-backed applications live web search through a single Amazon Bedrock AgentCore Gateway — with no search API keys on the client side, centralized access control through your existing identity provider, and an audit trail for every query.
What is AgentCore Gateway?
Amazon Bedrock AgentCore is a fully managed service for deploying, managing, and scaling AI agents in production. One of its components, AgentCore Gateway , acts as a centralized entry point that sits between your AI clients and the tools they call. It handles authentication, authorization, and routing — exposing tools through the Model Context Protocol (MCP) standard so any MCP-compatible client can discover and invoke them without custom integration code.
The problem with raw search API keys
If you want to give three AI surfaces (Claude Code, Claude Desktop, and a Bedrock backend) access to web search today, the direct approach looks like this:
- Provision a search API key from a third-party provider (Google, Bing, Tavily, etc.).
- Distribute that key to every developer machine and every backend service.
- Build your own rate-limiting, logging, and access-revocation layer.
- Repeat for each new tool you add (code search, documentation lookup, etc.).
This approach has three structural problems:
- Credential sprawl. Each client stores a copy of the API key. If any machine is compromised, you rotate the key everywhere.
- No identity-aware governance. You cannot restrict which users or roles are allowed to search, or audit who searched what, because the key is shared.
- Per-tool integration overhead. Every new tool requires a new key, a new distribution mechanism, and a new access-control layer.
How AgentCore Gateway solves this
AgentCore Gateway includes a built-in Web Search connector (
connectorId: web-search ) that eliminates all three problems:
Concern | Raw API key | AgentCore Gateway |
|---|---|---|
Credentials on client | Search API key stored locally | None — the gateway authenticates to the search service using its own IAM role |
Access control | Shared key, all-or-nothing | Per-user JWT validation against your identity provider |
Audit | Build your own logging | CloudTrail and gateway-level request logs |
Data egress | Queries sent to third-party search provider | Queries stay within AWS — served by an Amazon-operated web index |
Adding new tools | New key + new integration per tool | Add a target to the same gateway — clients discover it automatically via MCP |
The gateway authenticates outbound to the Web Search connector using its own IAM role (which needs the
bedrock-websearch:InvokeSearch permission). Inbound, it validates a JWT from your identity provider before proxying any request. Your AI clients never see search credentials.Two authentication patterns
Before connecting a client, you need to understand the two OAuth 2.0 flows the gateway supports:
- Authorization Code + PKCE (interactive). A human signs in through a browser. The client receives a short-lived token. Use this for Claude Code and Claude Desktop when a developer is present.
- Client Credentials (machine-to-machine). The application authenticates as itself — no human involved. Use this for backend services calling the Bedrock Converse API, or for Claude Desktop in headless/service-account scenarios.
Both flows produce a JWT that the gateway validates on every request. The gateway's
CUSTOM_JWT authorizer accepts tokens from any OIDC-compliant provider — Amazon Cognito, Microsoft Entra ID, Okta, Auth0, or your own.Prerequisites
Before you begin, you need an AgentCore Gateway with inbound authorization already configured. If you don't have one yet:
- For Cognito as your IdP, follow Build your first authenticated agent .
- For any IdP (Okta, Entra ID, Auth0), follow Building a secure auth code flow setup using AgentCore Gateway with MCP clients .
- For gateway creation specifically, see Create a gateway .
Once your gateway is
READY , come back here to add Web Search as a target.Add the Web Search target to your gateway
The Web Search Tool is a built-in connector — you don't deploy or host anything. The gateway handles schema management, endpoint resolution, and service authentication. Once added, MCP clients calling
tools/list on your gateway automatically discover a WebSearch tool they can invoke like any other MCP tool.Step 1: Grant the gateway's service role permission to invoke Web Search
The gateway calls the Web Search service using its own IAM role. That role needs the
bedrock-websearch:InvokeSearch action. Attach this identity-based policy to your gateway service role:{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowGatewayWebSearch", "Effect": "Allow", "Action": [ "bedrock-websearch:InvokeSearch" ], "Resource": "arn:aws:bedrock-websearch:*:aws:tool/WebSearch" } ]}Note: If you also want to allow the Web Fetch capability (retrieving full page content), addbedrock-websearch:InvokeFetchto theActionlist.
Step 2: Create the Web Search gateway target
Using the AWS CLI:
aws bedrock-agentcore-control create-gateway-target \ --gateway-identifier "$GATEWAY_ID" \ --name "WebSearchTarget" \ --target-configuration '{ "mcp": { "connector": { "source": { "connectorId": "web-search", "version": "1.2.0" } } } }' \ --credential-provider-configurations '[{ "credentialProviderType": "GATEWAY_IAM_ROLE" }]'Key parameters:
-
connectorId: "web-search"— tells the gateway this is the built-in Web Search connector, not a custom API.
-
version: "1.2.0"— pins to the latest connector version, which supports per-request domain and date filters. Omit to use the default version (currently 1.1.0).
-
credentialProviderType: "GATEWAY_IAM_ROLE"— the gateway authenticates to the Web Search service using its own role (the one you grantedbedrock-websearch:InvokeSearchabove). No separate credentials needed.
What the tool accepts and returns
Once added, the gateway exposes a
WebSearch tool with this input schema:Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Natural-language search query (max 200 characters) |
maxResults | integer | No | Number of results to return (1–25, default 10) |
filters.domainFilter.include | string[] | No | Only return results from these domains (v1.2.0+) |
filters.domainFilter.exclude | string[] | No | Drop results from these domains (v1.2.0+) |
filters.publishedDateFilter.from | string | No | Earliest publication date, ISO-8601 UTC (v1.2.0+) |
filters.publishedDateFilter.to | string | No | Latest publication date, ISO-8601 UTC (v1.2.0+) |
The tool returns MCP-compliant results with:
- text — semantically relevant snippets (not raw HTML)
- url — source webpage URL
- title — page title
- publishedDate — when the content was published
Results come from an Amazon-operated web index spanning tens of billions of documents. Queries stay entirely within AWS — they are not sent to any third-party search engine.
How the gateway makes this MCP-compliant
Without the gateway, the Web Search Tool is an AWS service with an IAM-authenticated API — not something Claude Code or Claude Desktop can call directly. The gateway wraps it in MCP: it manages the tool schema, handles authentication to the backend, and exposes the tool through
tools/list and tools/call on a standard MCP endpoint. Any MCP-compatible client (Claude Code, Claude Desktop, mcp-remote , Kiro, or your own MCP client) can discover and invoke it without knowing anything about IAM or the underlying service.Connect your clients
With the gateway running and Web Search available as a target, you can now connect any MCP-compatible client. Each client authenticates to the gateway using a JWT from your identity provider — the gateway handles the rest.
Connect Claude Code
Claude Code speaks MCP natively. Register the gateway as an MCP server:
claude mcp add --transport http agentcore-web-search \ "$GATEWAY_MCP_ENDPOINT"When the gateway returns a 401 challenge, Claude Code opens your browser for OAuth sign-in automatically (Authorization Code + PKCE). Some identity providers (including Cognito) require an exact-match redirect URI — they do not allow wildcard loopback ports. Register
http://localhost:<port>/callback in your IdP's app client to match the callback URL Claude Code uses during the OAuth flow.After authentication, the token is cached locally and refreshed automatically.
Test it: Run
/mcp inside Claude Code to confirm the web-search tool appears, then ask a time-sensitive question — for example, "What's new in the latest boto3 release?" — and watch it search and cite live sources.Connect Claude Desktop
Claude Desktop don't speak MCP-over-HTTP natively. They connect through
mcp-remote , a local proxy that bridges stdio-based MCP clients to HTTP-based MCP servers.Option A: interactive login (Authorization Code + PKCE)
Add the gateway to your
claude_desktop_config.json :{ "mcpServers": { "agentcore-web-search": { "command": "npx", "args": [ "mcp-remote", "$GATEWAY_MCP_ENDPOINT", "--oauth-callback-port", "8080" ] } }}On first connection,
mcp-remote opens a browser for sign-in — the same PKCE flow Claude Code uses.Option B: machine-to-machine (no browser)
For service accounts or headless environments, fetch a token via
client_credentials and pass it directly to mcp-remote :#!/usr/bin/env bashset -euo pipefail
TOKEN=$(curl -s -X POST "$TOKEN_ENDPOINT" \ -u "${CLIENT_ID}:${CLIENT_SECRET}" \ -d "grant_type=client_credentials&scope=gateway/access_as_user" \ | python3 -c 'import sys,json; print(json.load(sys.stdin)["access_token"])')
exec npx mcp-remote "$GATEWAY_MCP_ENDPOINT" \ --header "Authorization:Bearer ${TOKEN}"Point
claude_desktop_config.json at this wrapper script:{ "mcpServers": { "agentcore-web-search": { "command": "/path/to/agentcore-mcp-token-wrapper.sh" } }}macOS note: Claude Desktop's sandbox blocks script execution from
~/Documents , ~/Desktop , and similar user-data folders. Place the wrapper script in ~/Library/Application Support/Claude-3p/ to avoid Operation not permitted errors.Quit and relaunch Claude Desktop for the new configuration to take effect.
Connect Claude on Bedrock (Converse API)
If you call Claude models directly through the Amazon Bedrock Converse API — from your own backend, agent framework, or automation — the same gateway and Web Search connector work identically. Your application takes on the MCP client role that Claude Code and Claude Desktop handle for you.
The flow:
- Discover tools. Call
tools/liston the gateway's MCP endpoint to retrieve the Web Search tool schema.
- Pass tools to Converse. Include the tool schema in
toolConfigwhen calling the Converse API.
- Handle tool use. When the model returns
stopReason: "tool_use", extract the tool-call parameters, calltools/callon the gateway, and feed the result back.
- Repeat until done. Continue the loop until the model produces a final text response.
Because this is a non-interactive, server-side context, use the
client_credentials grant to obtain a token — no browser, no human.import requests, boto3, json
# 1. Get a machine-to-machine tokentoken_response = requests.post( TOKEN_ENDPOINT, auth=(CLIENT_ID, CLIENT_SECRET), data={"grant_type": "client_credentials", "scope": "gateway/access_as_user"})access_token = token_response.json()["access_token"]headers = {"Authorization": f"Bearer {access_token}"}
# 2. Discover tools from the gatewaytools_response = requests.post( f"{GATEWAY_MCP_ENDPOINT}", headers=headers, json={"jsonrpc": "2.0", "method": "tools/list", "id": 1})mcp_tools = tools_response.json()["result"]["tools"]
# 3. Convert MCP tools to Converse toolConfig formattool_config = {"tools": [ {"toolSpec": {"name": t["name"], "description": t["description"], "inputSchema": {"json": t["inputSchema"]}}} for t in mcp_tools]}
# 4. Converse loopbedrock = boto3.client("bedrock-runtime")messages = [{"role": "user", "content": [{"text": "What is new in Amazon Bedrock this week?"}]}]
while True: response = bedrock.converse( modelId="anthropic.claude-sonnet-4-20250514", messages=messages, toolConfig=tool_config ) output = response["output"]["message"] messages.append(output)
if response["stopReason"] != "tool_use": break # Model produced a final answer
# Execute each tool call against the gateway tool_results = [] for block in output["content"]: if "toolUse" in block: tool_call = block["toolUse"] call_response = requests.post( f"{GATEWAY_MCP_ENDPOINT}", headers=headers, json={"jsonrpc": "2.0", "method": "tools/call", "id": 2, "params": {"name": tool_call["name"], "arguments": tool_call["input"]}} ) tool_results.append({ "toolResult": {"toolUseId": tool_call["toolUseId"], "content": [{"text": json.dumps(call_response.json()["result"])}]} })
messages.append({"role": "user", "content": tool_results})
# Print final answerprint(output["content"][0]["text"])Note: This sample omits token refresh and error handling for brevity. In production, refresh the token before expiry and handle non-200 responses from both the gateway and the Converse API.
Important: Include theAuthorization: Bearer <token>header on every gateway call — bothtools/listand everytools/call. The gateway validates the token on each request independently. A missing header on either call returns a 401, even if the other succeeds.
Optional: Restrict searchable domains
If your organization wants to restrict which domains the Web Search connector can query (for example, block social media sites globally), configure a target-level domain filter. Unlike the per-request filters in the tool's input schema, target-level filters are enforced on every call and hidden from the calling agent:
{ "parameterValues": { "domainFilter": { "exclude": ["reddit.com", "twitter.com", "facebook.com"] } }}Pass this in the
--parameter-values argument when creating or updating the target. Target-level filters compose with per-request filters — a domain blocked at the target level cannot be overridden by an agent's request.Going further: policy, guardrails, and interceptors
Because the Web Search Tool is a standard gateway target, it benefits from every governance layer AgentCore Gateway provides — not just domain filtering.
AgentCore Policy (Cedar) lets you write fine-grained access rules evaluated on every
tools/call . For example, you can restrict web search to users with a specific role in their JWT ( principal.getTag("role") == "researcher" ), or block queries that match a sensitive pattern. Policies can run in ENFORCE mode (hard block) or LOG_ONLY mode (audit without blocking) while you tune them. See Policy in Amazon Bedrock AgentCore .Guardrails integrate with the Policy Engine to intercept requests before they reach the tool. A guardrail can detect and block profanity, harmful content, or off-topic queries in the search input — the same content filters you might apply to model prompts, applied here at the tool-invocation layer. See Getting started with guardrails .
Gateway Interceptors run custom logic (a Lambda function) on the request or response path. Use an interceptor to strip PII from outbound search queries before they reach the Web Search backend, or to redact sensitive content from search results before they flow back to the model. See Gateway Interceptors .
None of these are required to get web search working — the setup above is complete without them. But they illustrate why routing through a gateway is worth the initial setup: once the tool is behind the gateway, you can layer on governance incrementally without changing how any client connects.
Clean up
To avoid ongoing charges, delete the resources you created:
- Remove the Web Search target from the gateway. See Remove a target .
- Delete the AgentCore Gateway. See Delete a gateway .
- Delete the identity provider resources (Cognito user pool, app clients) if you created them for this walkthrough. See Deleting a user pool .
If you used the
mcp-remote wrapper script, remove it and the corresponding entry from claude_desktop_config.json .Conclusion
You set up a single AgentCore Gateway with Web Search, connected three AI surfaces to it, and gave each one live search capability — without distributing a single API key. Adding another tool (code search, documentation lookup, a private API) is the same pattern: add a target to the gateway, and every connected client discovers it automatically through MCP.
To get started, open the AgentCore console and create your first gateway, or follow the AgentCore Gateway documentation . For complete identity provider setup examples, explore the agentcore-samples repository under
integrations/identity-providers/ .Related reading
- Introducing Web Search on Amazon Bedrock AgentCore — deep dive into the Web Search Tool's architecture, index, and privacy model.
- Building a secure auth code flow setup using AgentCore Gateway with MCP clients — step-by-step OAuth setup with any IdP and Kiro IDE.
- Build your first authenticated agent — end-to-end Cognito walkthrough for AgentCore Identity.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article