Storefront / Guides / Bedrock Claude Managed Agents TypeScript Bridge
Amazon Bedrock · @anthropic-ai/bedrock-sdk@1.2.0 · TypeScript Architecture

Fixing Amazon Bedrock Claude Managed Agents' Web & ToolRunner Gaps in TypeScript

By Daniel Lopes Published Dec 2, 2026 11 min read Amazon Bedrock · Node.js 22+ · AsyncLocalStorage · SSRF IPv6 · IAM ABAC
Bedrock Claude Managed Agents TypeScript Bridge runtime pipeline with reentrancy-safe semaphores, SSRF IPv6 defense, 503 backoff, and 15 web tools

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 the web_fetch and web_search tools, so agent_toolset_20260401 holds only bash, read, write, edit, glob and grep. A request fails with a 400 error if a configs entry of an agent_toolset_20260401 tool names web_fetch or web_search, even with enabled: 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:

  1. Client-Side Typed Custom Tools (BedrockSessionToolBridge): Register strict JSON-Schema custom tools (for example web_read_markdown and web_agent_search) alongside { type: 'agent_toolset_20260401' } (with zero mention of web_fetch/web_search). Your TypeScript runtime handles agent.custom_tool_use events outside the sandbox, enforces SSRF + paid-call budgets, and posts clean Markdown results back.
  2. 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 an mcp_toolset to 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:

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]
>;
// 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:

  1. Reentrancy self-deadlock when sharing a semaphore: Suppose your BedrockSessionToolBridge calls concurrency.runTwoLevel('edge-api', ...) (which acquires sessionSemaphore then edgeApiSemaphore), and the underlying EdgeWebIntelClient also guards direct calls using the same edgeApiSemaphore. When edgeApiMaxConcurrency === 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.
  2. Queue overshoot on release: If release() decrements this.active-- and then wakes next.resolve() on the microtask queue, a brand-new caller arriving synchronously before the waiter resumes sees active < limit and steals a slot — silently exceeding maxConcurrentCalls.

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:

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:

  1. execution_identity role (passed to agents.create / sessions.create): Trust policy locked with aws:SourceAccount + aws:SourceArn (agent/* and session/*). 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-2 for claude-sonnet-4-6-v1:0) plus scoped bedrock-agentcore:InvokeGateway.
  2. 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, enforces s3:ResourceAccount and aws:SecureTransport: true, and intentionally omits s3:DeleteObject so 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).