banditdb-mcp
BanditDB Python SDK
BanditDB의 공식 Python 클라이언트 및 Model Context Protocol(MCP) 서버 — Rust로 작성된 초고속, 락-프리(Contextual Bandit) 데이터베이스입니다.
BanditDB는 강화학습(LinUCB, Thompson Sampling)의 복잡한 선형대수를 추상화하여 매우 간단한 API 뒤에 숨깁니다. 실시간 개인화 시스템, 동적 A/B 테스트를 구축하고 LLM 에이전트에게 수학적으로 엄밀한 영구 메모리를 제공하세요.
설치
pip install banditdb-pythonBanditDB Rust 서버가 실행 중이어야 합니다(기본값: http://localhost:8080).
Related MCP server: Copilot Memory Store
1. 표준 SDK 사용법
클라이언트는 자동 연결 풀링, 지수 백오프 재시도, 엄격한 타임아웃을 지원합니다.
from banditdb import Client, BanditDBError
# Connect to the BanditDB server.
# Pass api_key if BANDITDB_API_KEY is set on the server.
db = Client(
url="http://localhost:8080",
timeout=2.0,
api_key="your-secret-key", # omit if server runs without auth
)
try:
# 1. Create a campaign (run once at startup)
# algorithm defaults to "linucb"; use "thompson_sampling" for Bayesian exploration
db.create_campaign(
campaign_id="checkout_upsell",
arms=["offer_discount", "offer_free_shipping"],
feature_dim=3,
)
# or: db.create_campaign(..., algorithm="thompson_sampling")
# 2. A user arrives — ask the database what to show them
# Context: [is_mobile, cart_value_normalized, is_returning_user]
arm_id, interaction_id = db.predict("checkout_upsell", [1.0, 0.8, 0.0])
print(f"Showing: {arm_id}") # e.g., "offer_free_shipping"
# 3. The user clicked — send the reward
db.reward(interaction_id, reward=1.0)
except BanditDBError as e:
print(f"Database error: {e}")모든 클라이언트 메서드
헬스(Health)
메서드 | 설명 |
| 서버에 연결 가능하고 WAL 라이터가 정상이면 |
| 캠페인별 |
캠페인(Campaigns)
메서드 | 설명 |
| 새 캠페인을 등록합니다. |
|
|
|
|
| 비즈니스 수준 수렴 보고서입니다. |
| 운영자 진단: arm별 theta 노름, A_inv 불확실성 경계, 엔트로피 헬스( |
| 소프트 삭제: 예측/보상을 일시 중지하지만 학습된 모든 가중치는 보존합니다. |
| 보관된 캠페인을 모든 가중치를 유지한 채 활성 상태로 복원합니다. |
| 캠페인을 영구 삭제합니다. 찾을 수 없으면 |
예측 및 보상(Predict & Reward)
메서드 | 설명 |
|
|
| 단일 왕복으로 최대 100개의 캠페인/컨텍스트 쌍을 예측합니다. 각 항목: |
| 결과를 기록합니다. |
데이터 및 내보내기(Data & Export)
메서드 | 설명 |
| WAL을 플러시하고, 모델을 스냅샷하고, Parquet 샤드를 쓰고, 신경망 재학습 + 토너먼트 평가를 실행하고, WAL을 순환합니다. 요약 문자열을 반환합니다. |
| 캠페인별로 그룹화된 Parquet 내보내기 샤드 목록을 반환합니다. |
2. AI "하이브 마인드" (Model Context Protocol)
표준 LLM 에이전트는 상태가 없습니다(stateless) — 작업을 잘못된 모델로 라우팅하여 실패하면 다음 날 같은 실수를 반복합니다. BanditDB의 내장 MCP 서버는 전체 에이전트 스웜에 공유 영구 메모리를 제공합니다.
MCP 서버 시작
# Set environment variables before starting
export BANDITDB_URL=http://localhost:8080
export BANDITDB_API_KEY=your-secret-key # omit if server runs without auth
banditdb-mcpClaude Desktop에 연결
Claude 구성 파일에 추가하세요:
Mac:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"banditdb": {
"command": "banditdb-mcp",
"args": [],
"env": {
"BANDITDB_URL": "http://localhost:8080",
"BANDITDB_API_KEY": "your-secret-key"
}
}
}
}이제 에이전트 스웜은 9개의 도구를 사용할 수 있습니다:
도구 | 기능 |
| 새 의사결정 캠페인을 생성합니다. |
| 모든 활성 캠페인을 나열합니다( |
| arm별 학습 상태를 검사합니다: |
| 비즈니스 수준 수렴 보고서입니다. 캠페인이 통계적으로 수렴했는지, 신뢰구간과 함께 어떤 arm이 이기고 있는지 알려줍니다. |
| 주어진 컨텍스트에 대해 BanditDB에 어떤 arm을 선택할지 묻습니다. arm과 저장할 |
| 단일 왕복으로 여러 캠페인에 대한 결정을 얻습니다. |
| 선택한 행동이 성공(1.0)했는지 실패(0.0)했는지 보고합니다. 공유 모델을 업데이트합니다. |
| 캠페인을 소프트 삭제합니다. 예측/보상을 일시 중지하지만 학습된 모든 가중치는 보존합니다. |
| 보관된 캠페인을 모든 가중치를 유지한 채 활성 상태로 복원합니다. |
네트워크의 모든 에이전트가 내린 모든 결정은 향후 모든 에이전트의 라우팅을 개선합니다.
3. 데이터 사이언스 및 오프라인 평가
BanditDB는 모든 예측과 보상을 Write-Ahead Log(WAL)에 이벤트 소싱합니다. checkpoint()를 호출하면 완료된 예측→보상 쌍을 Polars 또는 Pandas로 오프라인 분석할 수 있도록 캠페인별로 하나씩 Snappy 압축 Parquet 파일로 컴파일합니다.
보상이 몇 시간 후에 도착하더라도 모든 예측이 Parquet 파일에 나타나는 것이 보장됩니다: BanditDB는 각 체크포인트에서 진행 중인 상호작용을 재발행하므로 지연된 보상은 항상 향후 주기에 캡처됩니다.
# Checkpoint: snapshot models, write Parquet, rotate the WAL.
# Call this on a schedule or after significant traffic.
summary = db.checkpoint()
print(summary)
# "Checkpoint written and WAL rotated: 2 campaigns, offset 4821 bytes,
# 150 interactions exported, 3 in-flight re-emitted"
# List which Parquet files are available
print(db.export())
# 'Parquet files in /data/exports: ["llm_routing.parquet"]'
# Load directly from the mounted volume into Polars.
# Flat schema: interaction_id | arm_id | reward | predicted_at | rewarded_at | propensity | feature_0 | ...
import polars as pl
df = pl.read_parquet("/data/exports/llm_routing.parquet")
print(df.head())
print(df.columns)오프라인 정책 평가(OPE)
SDK는 banditdb.eval에 세 가지 OPE 추정기를 제공합니다. 이들은 다음 질문에 답합니다: "라이브 실험을 실행하지 않고 다른 정책 하에서 내 평균 보상이 어땠을까?"
평가 종속성을 설치하세요:
pip install "banditdb-python[eval]"추정기 | 함수 | 작동 방식 | 사용 시기 |
Replay |
| 각 상호작용을 확률 | 기준선(sanity check)입니다. 낮은 커버리지가 예상됩니다 — 상호작용의 약 1/K만 사용됩니다. |
IPS / SNIPS |
| 중요도 가중치 | 기본 추정기입니다. 데이터가 충분하지만 전체 커버리지를 원할 때 사용하세요. |
Doubly Robust |
| 선형 보상 모델을 피팅한 다음 잔차에 IPS 보정을 적용합니다. 보상 모델 또는 propensity 중 하나가 정확하면 일관성이 있습니다. | 최상의 통계적 효율성입니다. 여러 정책을 비교하거나 |
세 가지 추정기 모두:
BanditDB Parquet 내보내기에서 로드된 Polars 또는 pandas DataFrame 허용
균일 무작위 정책을 대상으로 평가(이겨야 할 편향 없는 기준선)
Thompson Sampling 캠페인의 경우
ValueError발생(성향 열이 null — TS는 성향을 기록하지 않음)estimate,std_error,n_used,n_total,method를 포함한OPEResult반환
import polars as pl
from banditdb.eval import replay, ips, doubly_robust
df = pl.read_parquet("/data/exports/llm_routing.parquet")
# How much reward would a uniform random policy have earned?
print(replay(df))
# OPEResult(method='replay', estimate=0.4821, std_error=0.0312, coverage=22.1% [33/149])
print(ips(df))
# OPEResult(method='ips', estimate=0.5103, std_error=0.0187, coverage=100.0% [149/149])
print(doubly_robust(df))
# OPEResult(method='doubly_robust', estimate=0.5219, std_error=0.0141, coverage=100.0% [149/149])
# Compare against the observed reward of the logging policy:
print("Observed (logging policy):", df["reward"].mean())
# If observed >> estimate, the campaign has learned something real — it outperforms random.실용적 활용: 배포 전에 alpha를 오프라인으로 스윕하세요. 실제 트래픽으로 캠페인을 훈련하고 Parquet로 체크포인트한 다음, doubly_robust()를 통해 서로 다른 alpha 값을 재생하여 최적의 탐색 수준을 찾으세요 — 라이브 실험이 필요 없습니다.
참고: OPE에는
propensity열이 필요하며, 이 열은 LinUCB 캠페인에만 기록됩니다. Thompson Sampling 캠페인은null성향을 기록하는데, 이는 TS 팔 선택이 확률적이고 성향 점수 산정에는 결정적 로깅 정책이 필요하기 때문입니다.
알고리즘 선택
BanditDB는 캠페인 생성 시 선택할 수 있는 네 가지 알고리즘을 지원합니다.
알고리즘 |
| 탐색 방식 | 사용 시기 |
LinUCB |
| 결정적 UCB 보너스: | 예측 가능하고 조정 가능. |
Linear Thompson Sampling |
| θ̃ ~ N(θ, α²·A⁻¹) 샘플링, θ̃·x로 점수 산정 | 베이지안 사후 분포 — alpha 스윕 불필요. 동시 사용자가 자동으로 선택을 다양화. |
NeuralLinUCB |
| 딥 MLP 임베딩 + 임베딩 공간에서의 LinUCB | 비선형 보상 함수. N개의 보상마다 MLP를 재훈련. |
Progressive |
| 자동 튜닝 토너먼트: 기본 + 도전자를 병렬 실행, 승자에게 트래픽 이동 | 제로 구성 모델 선택. 최적의 알고리즘을 자동으로 선택. |
from banditdb import Client, NeuralLinUCBConfig, ProgressiveConfig
db = Client("http://localhost:8080")
# LinUCB (default)
db.create_campaign("routing", ["fast", "cheap"], feature_dim=4, alpha=1.5)
# Thompson Sampling — natural Bayesian exploration, alpha=1.0 is ideal
db.create_campaign("routing_ts", ["fast", "cheap"], feature_dim=4,
algorithm="thompson_sampling")
# NeuralLinUCB — learns a deep embedding of the context, then applies LinUCB
cfg = NeuralLinUCBConfig(
context_dim=4, # must match feature_dim
embed_dim=32, # arm matrix dimension (default 32)
hidden_dim=128, # MLP hidden layer width (default 128)
retrain_every=200, # retrain the MLP every N cumulative rewards
)
db.create_campaign("routing_neural", ["fast", "cheap"], feature_dim=4, algorithm=cfg)
# Progressive — runs LinUCB vs NeuralLinUCB, shifts traffic to whoever wins SNIPS checkpoints
cfg = ProgressiveConfig(
base="linucb",
challenger=NeuralLinUCBConfig(context_dim=4, embed_dim=32),
min_obs=100, # minimum buffer entries per arm before any traffic shift
required_wins=3, # consecutive checkpoint wins to earn one traffic step
step_bps=1000, # traffic delta per win run, in basis points (1000 = 10%)
)
db.create_campaign("routing_prog", ["fast", "cheap"], feature_dim=4, algorithm=cfg)네 가지 알고리즘 모두 동일한 predict → reward 루프를 공유합니다.
오류 처리
예외 | 발생 시점 |
| 기본 예외 — 모든 SDK 오류를 처리하려면 이를 포착하세요. |
| 서버가 오프라인이거나 연결할 수 없음. |
| 요청이 구성된 제한 시간을 초과함. |
| 서버가 오류를 반환함(예: 캠페인을 찾을 수 없음, 권한 없음). |
라이선스
Apache-2.0 — Copyright (C) 2026 Simeon Lukov and Dynamic Pricing Ltd. 자세한 내용은 메인 저장소를 참조하세요.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.
No tool schema history has been recorded yet.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Universal memory for AI agents and tools. Save, organize and search context anywhere.
Persistent memory and knowledge management for AI agents with semantic search and 50+ tools.
Shared, governed long-term memory for AI agents across tools and sessions via MCP and REST.
Persistent, inspectable memory for AI agents with lineage, correction, and a hosted MCP endpoint.
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables AI agents to record and rank learnings, facts, and methods through a collaborative voting framework. It provides tools for agents to surface the most useful information across sessions using persistent memory storage.8MIT
- AlicenseNot gradedqualityCmaintenanceEnables storing, searching, and compressing contextual memories for LLM interactions, with tools for memory management and context injection.9MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to store and recall persistent long-term memories across sessions using LanceDB, with semantic search, automatic linking, conflict detection, and maintenance tools.53MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to share persistent, conflict-safe memory by providing tools to recall, learn, reinforce, and retire lessons, using CockroachDB for storage and AWS Bedrock for embeddings.MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/dynamicpricing-ai/banditdb-python'
If you have feedback or need assistance with the MCP directory API, please join our Discord server