Fixing Amazon Bedrock Claude Managed Agents' Web & ToolRunner Gaps in TypeScript
If you installed @anthropic-ai/bedrock-sdk@1.2.0 to run Claude Managed Agents on Amazon Bedrock, you likely hit two hard walls on Day 1: Amazon Bedrock rejects native web_fetch and web_search with HTTP 400 (even when enabled: false), and BedrockEvents does not ship a .toolRunner() helper yet. This guide walks through the exact SDK source diff and the hardened TypeScript architecture we built to solve both gaps safely in production.
1. The SDK Source Diff: First-Party @anthropic-ai/sdk@1.16.0 vs @anthropic-ai/bedrock-sdk@1.2.0
Inspecting @anthropic-ai/bedrock-sdk/client.d.ts reveals why copy-pasting first-party Anthropic Managed Agents tutorials breaks immediately on AWS. Inside AnthropicBedrock, the beta namespace is explicitly overridden with Bedrock-specific resource classes:
// From @anthropic-ai/bedrock-sdk@1.2.0 (client.d.ts)
type BetaResource =
Omit<Resources.Beta, 'promptCaching' | 'messages' | 'userProfiles' | 'organization' | keyof Bedrock>
& Bedrock
& { messages: Omit<Resources.Beta['messages'], 'batches' | 'countTokens'> };
Because Bedrock shadows the first-party beta resources, client.beta.agents resolves to BedrockAgents, client.beta.sessions resolves to BedrockSessions, and client.beta.sessions.events resolves to BedrockEvents. That introduces six concrete wire differences you must design around from the start:
| Capability | First-Party @anthropic-ai/sdk@1.16.0 |
Amazon Bedrock bedrock-sdk@1.2.0 |
Production Fix |
|---|---|---|---|
Native web tools (web_fetch / web_search) |
Supported in agent_toolset_20260401 |
Blocked — HTTP 400 even with enabled: false |
Custom typed web tools or aws_agentcore_gateway OpenAPI 3.1 |
| Session event tool loop | SessionToolRunner / .toolRunner() |
BedrockEvents exposes only list(), send(), stream() |
BedrockSessionToolBridge + streamDispatches() generator |
| Model identifier format | Bare model ID (e.g. claude-sonnet-4-6) |
Geography-prefixed inference profile ID (us./eu./global.) |
Pin us.anthropic.claude-sonnet-4-6-v1:0 + IAM profile ARN |
| Document & Image inputs | Base64, text, URL, or file_id |
Base64 / text only (no URL or file_id) |
Fetch externally via SSRF-shielded Markdown tool |
| Session spend ceiling | Account / API-key billing limits | budget.max_list_cost.amount in minor USD strings ("500" = $5) |
createBedrockSessionSafe() fail-closed on region HTTP 400 + local cap |
| Sandbox cold starts & S3 mounts | Managed Anthropic sandbox | HTTP 503 StorageNotReadyError + separate S3 runtime role |
Exponential backoff + jitter + ABAC ${aws:PrincipalTag/session_id} |
2. Gap #1 — Why web_fetch and web_search Return HTTP 400 on Bedrock
Many teams hit an opaque 400 Bad Request on their very first bedrock.beta.agents.create() call because they carried over a defensive config explicitly setting web_fetch: { enabled: false }. The official TypeScript declaration in @anthropic-ai/sdk/resources/beta/bedrock/agents/agents.d.ts documents the exact server contract:
BetaManagedAgentsBedrockAgentToolParams(verbatim SDK declaration):
"Amazon Bedrock does not support theweb_fetchandweb_searchtools, soagent_toolset_20260401holds onlybash,read,write,edit,globandgrep. A request fails with a 400 error if aconfigsentry of anagent_toolset_20260401tool namesweb_fetchorweb_search, even withenabled: false."
Compounding that gap, BetaManagedAgentsBedrockDocumentBlock and BetaManagedAgentsBedrockImageBlock in events.d.ts explicitly forbid URL and file_id sources on Bedrock (base64 PDF/image or inline text only). Out of the box, your Bedrock Managed Agent cannot read documentation pages, audit SaaS pricing tables, inspect GitHub organizations, or query external REST endpoints.
There are two clean AWS-native ways to restore full web intelligence without giving the sandbox unrestricted egress:
- Client-Side Typed Custom Tools (
BedrockSessionToolBridge): Register strict JSON-Schemacustomtools (for exampleweb_read_markdownandweb_agent_search) alongside{ type: 'agent_toolset_20260401' }(with zero mention ofweb_fetch/web_search). Your TypeScript runtime handlesagent.custom_tool_useevents outside the sandbox, enforces SSRF + paid-call budgets, and posts clean Markdown results back. - Managed MCP via Amazon Bedrock AgentCore Gateway (
aws_agentcore_gateway): Import an OpenAPI 3.1 target specification into AgentCore Gateway and attach{ type: 'aws_agentcore_gateway', name, gateway_arn }plus anmcp_toolsetto the agent — offloading tool auth and execution to AWS while keeping the same REST endpoints.
3. Gap #2 — Building BedrockSessionToolBridge to Replace the Missing .toolRunner()
In @anthropic-ai/bedrock-sdk@1.2.0, BedrockEvents exposes only list(), send(), and stream(). To run custom tools reliably across single-agent and multi-agent coordinator sessions, your bridge must manage five invariants simultaneously:
- Deduplication by
event.id: Child coordinator thread events can surface across reconnects or streams; trackingseenToolUseIdsprevents double-executing paid tools. - Keeping the SSE stream open on
requires_action: Whensession.status_idlearrives withstop_reason.type === 'requires_action', the session is paused waiting for youruser.custom_tool_resultevents — do not break the loop until a terminal idle reason (end_turn,session.status_terminated, orsession.deleted) arrives. - Zero internal SDK imports: Importing
RequestOptionsfrom@anthropic-ai/sdk/internal/request-optionsbreaks under strict Node ESMexportsmaps. Derive it cleanly from the public method signature:
import type AnthropicBedrock from '@anthropic-ai/bedrock-sdk';
// Safe across Node 22 ESM strict package exports — zero internal path imports
export type BedrockRequestOptions = NonNullable<
Parameters<AnthropicBedrock['beta']['sessions']['events']['stream']>[2]
>;
- Fail-closed session budget creation (
createBedrockSessionSafe): Bedrock expresses session spend caps as minor-unit USD strings ({ type: 'limit', max_list_cost: { amount: '500', currency: 'USD' } }= $5.00). If a region rejectsbudgetwith HTTP 400, never silently drop the cap — throw a typedBedrockBudgetUnsupportedErrorunless the caller explicitly opts in viaallowUncappedFallback: true. - Bounded error forwarding: Catch per-tool exceptions, truncate output to
<= 30,000characters (matching@anthropic-ai/sdk@1.16.0), and return{ type: 'user.custom_tool_result', custom_tool_use_id: event.id, is_error: true, content: [...] }so Claude can recover instead of stalling the session.
// Core event-loop pattern inside BedrockSessionToolBridge.run()
const stream = await withStorageNotReadyRetry(
() => this.client.beta.sessions.events.stream(sessionId, this.streamParams, {
...this.requestOptions,
signal: combinedSignal,
}),
{ ...this.retryOptions, signal: combinedSignal },
);
for await (const event of stream) {
if (combinedSignal.aborted) break;
if (event.type === 'agent.custom_tool_use') {
if (seenToolUseIds.has(event.id)) continue;
seenToolUseIds.add(event.id);
const task = this.handleCustomToolUse(sessionId, event, combinedSignal);
inFlight.add(task);
void task.finally(() => inFlight.delete(task));
continue;
}
if (event.type === 'session.status_idle') {
const idleReason = event.stop_reason?.type ?? 'idle';
if (idleReason === 'requires_action') continue; // Wait for in-flight tool results
stopReason = idleReason;
break;
}
}
4. Preventing Deadlocks & Thundering Herds in Multi-Agent Coordinators (AsyncLocalStorage Semaphores)
Bedrock Managed Agents natively support multiagent: { type: 'coordinator', agents: [...] } topologies that spawn up to 20 specialist sub-threads. Without concurrency control, a coordinator can fire 15 parallel custom tool calls in one burst — tripping upstream API rate limits or burning paid credits.
During our OWASP ASVS security review, we caught two subtle concurrency bugs that bite almost every hand-rolled TypeScript semaphore:
- Reentrancy self-deadlock when sharing a semaphore: Suppose your
BedrockSessionToolBridgecallsconcurrency.runTwoLevel('edge-api', ...)(which acquiressessionSemaphorethenedgeApiSemaphore), and the underlyingEdgeWebIntelClientalso guards direct calls using the sameedgeApiSemaphore. WhenedgeApiMaxConcurrency === 1(or when all slots are held by outer callers), the inner client attempts to acquire a second slot on the semaphore its own call chain already holds — causing a deterministic deadlock. - Queue overshoot on release: If
release()decrementsthis.active--and then wakesnext.resolve()on the microtask queue, a brand-new caller arriving synchronously before the waiter resumes seesactive < limitand steals a slot — silently exceedingmaxConcurrentCalls.
The clean Node.js 22 solution pairs AsyncLocalStorage<ReadonlySet<AsyncSemaphore>> with atomic slot handoff inside createReleaser():
import { AsyncLocalStorage } from 'node:async_hooks';
const heldSemaphores = new AsyncLocalStorage<ReadonlySet<AsyncSemaphore>>();
export class AsyncSemaphore {
readonly limit: number | null;
private active = 0;
private readonly queue: Array<{ resolve: () => void; reject: (err: unknown) => void }> = [];
constructor(limit: number | null) {
if (limit !== null && (!Number.isInteger(limit) || limit < 1)) {
throw new RangeError(`maxConcurrentCalls must be an integer >= 1 or null (got ${String(limit)})`);
}
this.limit = limit;
}
async run<T>(fn: () => Promise<T>, signal?: AbortSignal | null): Promise<T> {
if (signal?.aborted) throw signal.reason ?? new Error('Operation aborted');
// Reentrancy guard: if this async chain already holds this semaphore, pass through safely
const currentHeld = heldSemaphores.getStore();
if (currentHeld?.has(this)) {
return await fn();
}
const release = await this.acquire(signal);
const nextHeld = new Set(currentHeld);
nextHeld.add(this);
try {
return await heldSemaphores.run(nextHeld, fn);
} finally {
release();
}
}
private createReleaser(): () => void {
let released = false;
return () => {
if (released) return;
released = true;
const next = this.queue.shift();
if (next) {
// Atomic handoff: `this.active` stays constant so concurrent arrivals cannot overshoot `limit`
next.resolve();
} else {
this.active--;
}
};
}
}
Pair this with a shared fail-closed PaidToolCallBudget (MAX_PAID_TOOL_CALLS_PER_SESSION=25 by default in fromEnv(), opt-out only via explicit budget: null). Always call budget.consume() inside the semaphore after SSRF validation and signal.aborted checks — so blocked SSRF attempts or cancelled requests never leak paid budget units.
5. Surviving Sandbox Cold Starts (503), Untrusted URLs (SSRF IPv6), & IAM ABAC
A. Retrying Real 503 StorageNotReadyError Responses
When a Bedrock Managed Agents sandbox provisions or mounts S3 storage on cold start, sessions.create(), events.stream(), and events.send() can return HTTP 503 with error_code: "storage_not_ready". The SDK instantiates StorageNotReadyError from @anthropic-ai/sdk/resources/shared. Wrap every session and event call in an AbortSignal-aware retry loop that respects both exponential backoff + jitter and upstream Retry-After headers:
import { StorageNotReadyError } from '@anthropic-ai/sdk/resources/shared';
export function isStorageNotReadyError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false;
if (error instanceof StorageNotReadyError) return true;
const e = error as { status?: number; details?: { error_code?: string }; message?: string };
return e.status === 503 && (
e.details?.error_code === 'storage_not_ready' ||
Boolean(e.message?.includes('storage_not_ready'))
);
}
B. Full IPv4 + IPv6 SIIT / NAT64 / Teredo SSRF Shield
Whenever a Bedrock agent passes a model-generated URL into a custom web tool, treat it as untrusted input. A naive regex checking for 127.0.0.1 and 169.254.169.254 (AWS EC2/ECS IMDS) is trivially bypassed using decimal IP literals (2130706433), octal notation (0177.0.0.1), DNS rebinding, or IPv6 translation prefixes.
Our fail-closed SSRF Shield (verifyDns: true by default in fromEnv()) runs pre-flight syntax checks, resolves all A/AAAA records via dns.lookup(host, { all: true, verbatim: true }), and expands every IPv6 address into 8 canonical 16-bit groups to explicitly block:
- IPv4 private/reserved blocks:
0.0.0.0/8, RFC1918 (10/8,172.16/12,192.168/16), CGNAT (100.64/10), loopback (127/8), AWS IMDS link-local (169.254/16), multicast/broadcast (>= 224). - IPv6 native & translation bypasses: loopback (
::1), unspecified (::), ULA (fc00::/7), link-local (fe80::/10), IPv4-mapped (::ffff:0:0/96), RFC 2765/6890 SIIT IPv4-translated (::ffff:0:0:0/96), RFC 8215 Local-Use NAT64 (64:ff9b:1::/48), RFC 6052 Well-Known NAT64 (64:ff9b::/96), RFC 4380 Teredo (2001:0000::/32), and 6to4 (2002::/16). - Execution ceilings: strict
<= 30,000-character payload truncation plusAbortSignal.anytimeouts (30ssub-second Edge API /120sbatch Apify Actors / hard cap< 300s).
C. IAM Least-Privilege & ABAC Session Isolation
One of the most frequent AWS security mistakes with Bedrock Managed Agents is granting wildcard bedrock:* and s3:* on a single role. Per the Bedrock v1.2.0 architecture, always separate two distinct IAM roles:
execution_identityrole (passed toagents.create/sessions.create): Trust policy locked withaws:SourceAccount+aws:SourceArn(agent/*andsession/*). Permissions pinned solely to your explicit inference profile ARN and its US cross-region foundation model ARNs (us-east-1,us-east-2,us-west-2forclaude-sonnet-4-6-v1:0) plus scopedbedrock-agentcore:InvokeGateway.- AgentCore Runtime S3 Sandbox role (referenced by
environment_id): Uses Attribute-Based Access Control (ABAC) via${aws:PrincipalTag/session_id}so concurrent sessions cannot read or overwrite another tenant's workspace, enforcess3:ResourceAccountandaws:SecureTransport: true, and intentionally omitss3:DeleteObjectso an agent cannot wipe audit artifacts:
{
"Sid": "ReadWriteOutputsPrefixNoDelete",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::YOUR_AGENT_BUCKET/agent-outputs/${aws:PrincipalTag/session_id}/*",
"Condition": {
"StringEquals": { "s3:ResourceAccount": "123456789012" },
"Bool": { "aws:SecureTransport": "true" }
}
}
6. Wire-Level Contract Testing at $0.00 AWS Cost (And the SDK SSE event: Trap)
You should never need live AWS Bedrock spend just to verify your tool bridge, concurrency caps, 503 retries, and SSRF guardrails in CI. Because AnthropicBedrock accepts a custom baseURL, you can test the real SDK client end-to-end against a deterministic local Node.js HTTP/SSE contract server:
const bedrock = new AnthropicBedrock({
baseURL: `http://127.0.0.1:${mockPort}`,
apiKey: 'local-contract-test-key',
awsRegion: 'us-east-1',
});
Crucial SDK Gotcha: When building a local SSE mock server for @anthropic-ai/bedrock-sdk@1.2.0, every frame must include an explicit event: line before data:. Inspecting @anthropic-ai/sdk/core/streaming.mjs shows that frames where sse.event === null are silently discarded rather than yielded:
// REQUIRED: always emit both `event:` and `data:` lines in SSE contract mocks
res.write(`event: agent.custom_tool_use\n`);
res.write(`data: ${JSON.stringify(toolUseEvent)}\n\n`);
Using this pattern, our full test harness runs 67/67 Vitest assertions + 3/3 mutation proofs with tsc --noEmit (0 errors, 0 @ts-ignore) at $0.00 AWS spend. Once CI is green, live AWS verification (IAM role assumption, AgentCore Runtime V2 ARN, S3 mounts, and live Claude Sonnet 4.6 inference) takes under 60 seconds via npm run smoke:bedrock inside your AWS staging account.
7. Start Free (MIT) or Deploy the Full 15-Tool Enterprise Kit
Everything in this architecture is available as an auditable MIT-licensed TypeScript starter bridge you can run locally in 2 minutes, or as a complete commercial production kit with all 15 web/B2B tools, dual-mode SDK wrappers, and AWS Enterprise IAM/AgentCore templates.
Ship Production Bedrock Claude Managed Agents on Day 1
Clone the free MIT BedrockSessionToolBridge (2 SSRF-shielded web tools + 503 backoff) to verify the wire contract at $0.00, grab the Commercial PRO Kit ($49 one-time) with 15 Edge/Apify tools and AWS Enterprise IAM/AgentCore templates, or book a fixed-price done-for-you AWS setup on Upwork ($295 / $545 / $950).