MCPcopy Index your code
hub / github.com/coder/aibridge

github.com/coder/aibridge @v1.1.2

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.1.2 ↗ · + Follow
721 symbols 3,437 edges 95 files 242 documented · 34%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

aibridge

aibridge is an HTTP gateway that sits between AI clients and upstream AI providers (Anthropic, OpenAI). It intercepts requests to record token usage, prompts, and tool invocations per user. Optionally supports centralized MCP tool injection with allowlist/denylist filtering.

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.Handler that 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

  1. Client sends request to /anthropic/v1/messages or /openai/v1/chat/completions
  2. Actor extraction: Request must have an actor in context (via AsActor()).
  3. Upstream call: Request forwarded to the AI provider
  4. Response relay: Response streamed/sent to client
  5. 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
tokens_total Counter Token usage (input/output)
prompts_total Counter User prompt count
injected_tool_invocations_total Counter MCP tool invocations
passthrough_total Counter Non-intercepted requests

Recorder Interface

Implement Recorder to persist usage data to your database. The example uses SQLite (example/recorder.go):

  • aibridge_interceptions - request metadata (provider, model, initiator, timestamps)
  • aibridge_token_usages - input/output token counts per response
  • aibridge_user_prompts - user prompts
  • aibridge_tool_usages - tool invocations (injected and client-defined)
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
}

Example

See example/ for a complete runnable example with SQLite persistence and DeepWiki MCP integration.

Setup

  1. Get API keys from the provider consoles:
  2. Anthropic: https://console.anthropic.com/settings/keys
  3. OpenAI: https://platform.openai.com/api-keys

  4. Set environment variables: bash export ANTHROPIC_API_KEY="sk-ant-..." export OPENAI_API_KEY="sk-..."

  5. Run the example: bash cd example && go run .

  6. Test with curl: bash curl -X POST http://localhost:8080/anthropic/v1/messages \ -H "Content-Type: application/json" \ -d '{ "model": "claude-sonnet-4-20250514", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello!"}], "stream": true }'

  7. Test with Claude Code: Claude Code allows a base URL override via ANTHROPIC_BASE_URL.

image with claude code example

Supported Routes

Provider Route Type
Anthropic /anthropic/v1/messages Bridged (intercepted)
Anthropic /anthropic/v1/models Passthrough
Anthropic /anthropic/v1/messages/count_tokens Passthrough
OpenAI /openai/v1/chat/completions Bridged (intercepted)
OpenAI /openai/v1/models Passthrough

Extension points exported contracts — how you extend this code

ServerProxier (Interface)
ServerProxier provides an abstraction to communicate with MCP Servers regardless of their transport. The ServerProxier i [5 …
mcp/api.go
ToolCaller (Interface)
ToolCaller is the narrowest interface which describes the behavior required from [mcp.Client], which will normally be pa [5 …
mcp/tool.go
Recorder (Interface)
Recorder describes all the possible usage information we need to capture during interactions with AI providers. Addition [4 …
recorder/types.go
Provider (Interface)
Provider defines routes (bridged and passed through) for given provider. Bridged routes are processed by dedicated inter [4 …
provider/provider.go
Interceptor (Interface)
Interceptor describes a (potentially) stateful interaction with an AI provider.
intercept/interceptor.go

Core symbols most depended-on inside this repo

Get
called by 152
circuitbreaker/circuitbreaker.go
Error
called by 124
intercept/messages/base.go
PtrTo
called by 81
utils/ptr.go
Close
called by 74
intercept/apidump/streaming.go
newBridgeTestServer
called by 44
internal/integrationtest/setupbridge.go
makeRequest
called by 43
internal/integrationtest/setupbridge.go
Write
called by 35
intercept/responses/base.go
Parse
called by 35
fixtures/fixtures.go

Shape

Method 349
Function 284
Struct 73
TypeAlias 8
Interface 6
FuncType 1

Languages

Go100%

Modules by API surface

intercept/responses/base.go25 symbols
intercept/messages/base.go24 symbols
recorder/recorder.go22 symbols
provider/openai_test.go22 symbols
intercept/chatcompletions/streaming.go21 symbols
internal/testutil/mock_recorder.go20 symbols
internal/integrationtest/bridge_test.go19 symbols
intercept/chatcompletions/base.go19 symbols
internal/integrationtest/mockupstream.go17 symbols
circuitbreaker/circuitbreaker.go17 symbols
intercept/messages/reqpayload.go16 symbols
recorder/types.go15 symbols

For agents

$ claude mcp add aibridge \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact