AI Bridge failed any Anthropic Messages stream whose events the SDK
accumulator rejected. The common case is a response that stops at
`max_tokens` inside a `tool_use` block: the tool input JSON is
truncated, the pinned SDK's `Accumulate` fails when it marshals that
input on `content_block_stop` or `message_stop`, and the interceptor
stopped relaying and sent the client an SSE `error` (`processing error:
accumulate event: ...`). The client lost the rest of the response,
including the `max_tokens` stop reason it needed to recover. Coder
Agents treats that error as non-retryable, so the chat ended in an error
state.
Relaying does not depend on a successful accumulate; only injected MCP
tools execute the accumulated input. This PR:
- Logs the first accumulate error in each iteration and keeps relaying
events.
- Clears pending injected tool calls when a `message_delta` carries a
stop reason other than `tool_use` (for example `max_tokens`), so AI
Bridge never runs an MCP tool on truncated input or sends that input
back upstream. An interim `message_delta` without a stop reason keeps
them.
- Still fails the stream when accumulation failed and injected tool
calls are pending at `message_stop`: their accumulated input cannot be
trusted, and the client never saw those calls.
- Also fails the stream when accumulation failed and the upstream closes
before `message_stop`, so the client still gets a terminal event. A
client cancel is not reported as an accumulation failure.
- Records tool usage from `block.Input`, as a string when it is not
valid JSON. After a failed accumulate, `variant.Input` holds the stale
`{}` from `content_block_start`.
Other accumulator errors, such as `invalid character '}'`, are handled
the same way.
Related: #30120 makes chatd answer the cut-off call with a tool error
that tells the model to split its input.
Follow-up, out of scope: upgrading `anthropic-sdk-go` from the pinned
v1.19.0 fork. A probe upgrade to v1.76.0 fails two existing tests
(injected-tool content block indices and the Bedrock eventstream path).
## Testing
- `TestAnthropicMessages/streaming builtin tool truncated by
max_tokens`, with and without `content_block_stop`: the client receives
every event in order through `message_stop` with no `error` event, the
interception ends without an error, and the tool usage is recorded with
the truncated input.
- `TestAnthropicMessages/streaming injected tool with invalid input`:
with `stop_reason: max_tokens` the client receives the stop reason and
`message_stop`, the MCP tool is never called, and AI Bridge makes one
upstream request. With `stop_reason: tool_use`, or when the upstream
closes before `message_stop`, the stream ends with an `accumulate event`
error instead of calling the tool.
- `TestAnthropicMessages/streaming injected tool with interim
message_delta`: a `message_delta` with a null stop reason before the
`tool_use` delta still runs the MCP tool.
- Red-green: with `streaming.go` restored to the base code, the three
truncation cases fail. The `tool_use` case passes on the base code by
design, since the old code failed every such stream; removing the new
`message_stop` guard makes the MCP tool run with the stale `{}` input.
- `go test ./aibridge/... -count=1` and `golangci-lint run
./aibridge/...` pass. Local pre-push checks were skipped per standing
preference; PR CI covers them.
- Remote UAT: not run yet.
## Review record
- Parent review (Xum) of `383dda920d6`: the remaining `message_stop`
guard had no test. Fixed in `5ea664affbf`.
- Codex round 1 on `5ea664affbf`: 1 P2, a clean upstream close after a
failed accumulate ended the response without a terminal event and
recorded success. Reproduced by the new `upstream closes before
message_stop` case (red on `5ea664affbf`) and fixed in `72bdc10e77b`.
- Codex round 2 on `72bdc10e77b`: 1 P1 and 1 P2. P1: an interim
`message_delta` without a stop reason cleared pending injected tools;
reproduced by the new interim delta case (red on `72bdc10e77b`) and
fixed in `73a7ba2a9a8`. P2: a client cancel after a failed accumulate
was promoted to a server error; confirmed by code trace (no
deterministic test for a cancel between `Next` and `Send`) and fixed in
`73a7ba2a9a8` by promoting only where the upstream stream ends.
- Codex round 3 on `73a7ba2a9a8`: no findings.
> Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike.
aibridge
aibridge provides an HTTP handler that intercepts AI client requests bound for upstream AI providers (Anthropic, OpenAI, Copilot). It records token usage, prompts, and tool invocations per user. Optionally supports centralized MCP tool injection with allowlist/denylist filtering.
The handler is mounted by a host process. Today that host is coderd, which mounts the handler at /api/v2/ai-gateway/<provider>/*. Running aibridge as a separate process is planned for the future.
Architecture
┌─────────────────┐ ┌───────────────────────────────────────────┐
│ AI Client │ │ aibridge │
│ (Claude Code, │────▶│ ┌─────────────────┐ ┌─────────────┐ │
│ Cursor, etc.) │ │ │ RequestBridge │───▶│ Providers │ │
└─────────────────┘ │ │ (http.Handler) │ │ (Anthropic │ │
│ └─────────────────┘ │ OpenAI) │ │
│ └──────┬──────┘ │
│ │ │
│ ▼ │ ┌─────────────┐
│ ┌─────────────────┐ ┌─────────────┐ │ │ Upstream │
│ │ Recorder │◀───│ Interceptor │─── ───▶│ API │
│ │ (tokens, tools, │ │ (streaming/ │ │ │ (Anthropic │
│ │ prompts) │ │ blocking) │ │ │ OpenAI) │
│ └────────┬────────┘ └──────┬──────┘ │ └─────────────┘
│ │ │ │
│ ▼ ┌──────▼──────┐ │
│ ┌ ─ ─ ─ ─ ─ ─ ─ ┐ │ MCP Proxy │ │
│ │ Database │ │ (tools) │ │
│ └ ─ ─ ─ ─ ─ ─ ─ ┘ └─────────────┘ │
└───────────────────────────────────────────┘
Components
- RequestBridge: The main
http.Handlerthat routes requests to providers - Provider: Defines bridged routes (intercepted) and passthrough routes (proxied)
- Interceptor: Handles request/response processing and streaming
- Recorder: Interface for capturing usage data (tokens, prompts, tools)
- MCP Proxy (optional): Connects to MCP servers to list tool, inject them into requests, and invoke them in an inner agentic loop
Request Flow
- Client sends request to
/anthropic/v1/messagesor/openai/v1/chat/completions - Actor extraction: Request must have an actor in context (via
AsActor()). The host is responsible for authenticating the caller before invoking the handler. - Upstream call: Request forwarded to the AI provider
- Response relay: Response streamed/sent to client
- Recording: Token usage, prompts, and tool invocations recorded
With MCP enabled: Tools from configured MCP servers are centrally defined and injected into requests (prefixed bmcp_). Allowlist/denylist regex patterns control which tools are available. When the model selects an injected tool, the gateway invokes it in an inner agentic loop, and continues the conversation loop until complete.
Passthrough routes (/v1/models, /v1/messages/count_tokens) are reverse-proxied directly.
Observability
Prometheus Metrics
Create metrics with NewMetrics(prometheus.Registerer):
| Metric | Type | Description |
|---|---|---|
interceptions_total |
Counter | Intercepted request count |
interceptions_inflight |
Gauge | Currently processing requests |
interceptions_duration_seconds |
Histogram | Request duration |
passthrough_total |
Counter | Non-intercepted requests forwarded to the upstream |
prompts_total |
Counter | User prompt count |
tokens_total |
Counter | Token usage (input, output, cache read/write, provider extras) |
injected_tool_invocations_total |
Counter | Injected MCP tool invocations performed by the handler |
non_injected_tool_selections_total |
Counter | Client-defined tool selections returned by the model |
circuit_breaker_state |
Gauge | Circuit breaker state per provider/endpoint (0=closed, 0.5=half, 1=open) |
circuit_breaker_trips_total |
Counter | Times the circuit breaker transitioned to open |
circuit_breaker_rejects_total |
Counter | Requests rejected due to an open circuit breaker |
Recorder Interface
Implement Recorder to persist usage data to your database:
aibridge_interceptions- request metadata (provider, model, initiator, timestamps)aibridge_token_usages- input/output and cache read/write token counts per responseaibridge_user_prompts- user promptsaibridge_tool_usages- tool invocations (injected and client-defined)aibridge_model_thoughts- model reasoning content (thinking, reasoning summaries, commentary)
type Recorder interface {
RecordInterception(ctx context.Context, req *InterceptionRecord) error
RecordInterceptionEnded(ctx context.Context, req *InterceptionRecordEnded) error
RecordTokenUsage(ctx context.Context, req *TokenUsageRecord) error
RecordPromptUsage(ctx context.Context, req *PromptUsageRecord) error
RecordToolUsage(ctx context.Context, req *ToolUsageRecord) error
RecordModelThought(ctx context.Context, req *ModelThoughtRecord) error
}
Supported Routes
Each provider instance is mounted under /api/v2/ai-gateway/<name>, where <name> is the provider's configured name. For example, with an Anthropic provider named my-anthropic, its /messages endpoint would be reachable at /api/v2/ai-gateway/my-anthropic/v1/messages.
If a name is not set, the route path defaults to the provider's type: anthropic, openai, or copilot. The table below uses the default names.
(/*) denotes a route that handles both the exact path and any subpaths. A trailing /* denotes subpaths only.
| Provider | Route | Type |
|---|---|---|
| Anthropic | /anthropic/v1/messages |
Bridged (intercepted) |
| Anthropic | /anthropic/v1/messages/count_tokens |
Passthrough |
| Anthropic | /anthropic/v1/models(/*) |
Passthrough |
| Anthropic | /anthropic/api/event_logging/* |
Passthrough |
| OpenAI | /openai/v1/chat/completions |
Bridged (intercepted) |
| OpenAI | /openai/v1/responses |
Bridged (intercepted) |
| OpenAI | /openai/v1/responses/* |
Passthrough |
| OpenAI | /openai/v1/conversations(/*) |
Passthrough |
| OpenAI | /openai/v1/models(/*) |
Passthrough |
| Copilot | /copilot/chat/completions |
Bridged (intercepted) |
| Copilot | /copilot/responses |
Bridged (intercepted) |
| Copilot | /copilot/models(/*) |
Passthrough |
| Copilot | /copilot/agents/* |
Passthrough |
| Copilot | /copilot/mcp/* |
Passthrough |
| Copilot | /copilot/.well-known/* |
Passthrough |