Skip to main content
Glama
io.github.TheTsungYing/annealbridge

io.github.TheTsungYing/annealbridge

AnnealBridge

CI PyPI Python 3.11+ License: MIT

English | 繁體中文

Combinatorial optimization middleware for AI agents. An agent describes what to optimize as structured JSON; AnnealBridge decides how to encode and solve it, checks every answer against the original problem, and returns ranked, verified solutions over MCP, a CLI, or plain Python.

flowchart LR
    U[Natural language] --> A[AI agent]
    A -->|OptimizationProblem JSON<br/>variables · objective · constraints| B
    subgraph B[AnnealBridge]
        direction LR
        V[validate] --> C[compile<br/>BQM / CQM] --> S[solve<br/>local or remote] --> R[re-validate against<br/>the original problem] --> K[rank]
    end
    B -->|SolveResult<br/>ranked, verified solutions| A
    A --> N[Natural-language answer]

Quick start

pip install annealbridge

A 0/1 knapsack: four items, capacity 10, maximize value. No file needed.

from annealbridge.models import OptimizationProblem
from annealbridge.orchestration import OptimizationService

problem = OptimizationProblem.model_validate({
    "version": "1.0",
    "name": "knapsack",
    "variables": [{"name": n, "type": "binary"} for n in ["a", "b", "c", "d"]],
    "objective": {"direction": "maximize", "linear_terms": [
        {"variable": "a", "coefficient": 10}, {"variable": "b", "coefficient": 8},
        {"variable": "c", "coefficient": 7}, {"variable": "d", "coefficient": 6}]},
    "constraints": [{"id": "capacity", "type": "hard", "operator": "<=", "rhs": 10, "terms": [
        {"variable": "a", "coefficient": 6}, {"variable": "b", "coefficient": 5},
        {"variable": "c", "coefficient": 4}, {"variable": "d", "coefficient": 3}]}],
})

result = OptimizationService().solve(problem)
print(result.status)                        # success
print(result.solutions[0].variables)        # {'a': 1, 'b': 0, 'c': 1, 'd': 0}
print(result.solutions[0].objective_value)  # 17.0

Domain failures come back as results, never as exceptions: result.status is one of success, infeasible, invalid_problem, resource_limit_exceeded, backend_unavailable, configuration_error or solver_error. See docs/output-format.md.

Optional extras:

pip install "annealbridge[mcp]"       # + MCP server (annealbridge-mcp)
pip install "annealbridge[dwave]"     # + D-Wave cloud backends
pip install "annealbridge[all]"       # everything
pip install "annealbridge[gpu]"       # + PyTorch, for simulated_bifurcation on CUDA

[gpu] is deliberately not part of [all]: PyTorch is a large download, and on Windows the wheel PyPI serves is the CPU-only build, so a CUDA run needs torch installed from PyTorch's own index first — see docs/backends.md.

Related MCP server: Gurddy MCP Server

Use it from an AI agent (MCP)

With uv installed, add the server to claude_desktop_config.json (or your host's equivalent) and restart the host; where Claude Desktop, Claude Code and Codex keep that configuration is listed in docs/mcp.md. The first run fetches the package into uvx's own cached environment; that download — numpy, dimod, dwave-samplers and the rest — can take tens of seconds, long enough for a host's start-up timeout to show the server as disconnected. Warm the cache once in a terminal first:

uvx --from "annealbridge[mcp]" annealbridge-mcp --version

It resolves the environment and prints the version; from then on the host starts from that cache.

{
  "mcpServers": {
    "annealbridge": {
      "command": "uvx",
      "args": ["--from", "annealbridge[mcp]", "annealbridge-mcp"]
    }
  }
}

Claude Code registers it in one line:

claude mcp add annealbridge -- uvx --from "annealbridge[mcp]" annealbridge-mcp

Optimizing is then an ordinary chat:

You: I can carry 10 kg. Item A is worth 10 and weighs 6, B is worth 8 and weighs 5, C is worth 7 and weighs 4, D is worth 6 and weighs 3. Which ones should I take?

Behind the reply, the agent writes the request as problem JSON and calls solve_optimization. Every solution comes back re-validated against the original constraints, with optimality_proven: true on the exhaustive exact backend; a document the server rejects comes back as invalid_problem with every error and a fix for each, which the agent applies before sending it again. Before solving on a remote backend, or on a large problem, it calls validate_optimization_problem first, so a mistake costs nothing; it calls get_optimization_capabilities when it needs the backend list or the full schema.

Agent: Take A and C: value 17 at exactly 10 kg. The runners-up are A and D (16, at 9 kg) and B and C (15, at 9 kg). This is the proven optimum.

The wording is the agent's; the numbers are the tool result. Another tool, recommend_backend, ranks the backends for a problem and is advisory only; when you did not name a backend and more than one local backend fits, the server instructions tell the agent to show the top entries and ask which to run rather than to decide for you.

If your host lists prompts in its input menu, three of them — pick_subset, assign and schedule_shifts — walk the agent from your own sentence to a problem document of that everyday shape, which it then solves. The server also serves resources: the seven example documents under annealbridge://examples/ and the full problem schema at annealbridge://schema, so an agent can read a complete example or the schema itself instead of guessing.

What it is not for. AnnealBridge does not handle continuous (real-valued) variables, non-linear objectives or non-linear constraints. Only exact proves that an answer is optimal or that no feasible one exists, and by default it takes at most 24 compiled variables (slack bits included); the other local backends (simulated_annealing, tabu, simulated_bifurcation) are heuristics whose best answer may not be the optimum. See the Backends table below and docs/limitations.md.

Any stdio-capable MCP host works the same way, a streamable-http transport exists, and pipx or a pip-installed server behind an absolute path work in place of uvx. uvx reuses the environment it resolved on its first run, so a new release reaches an existing install only after uv cache clean annealbridge and a host restart; see docs/mcp.md.

Use it from the command line

Save the problem JSON below as knapsack.json, then:

annealbridge solve knapsack.json
Problem:   knapsack
Backend:   exact
Status:    success
Attempts:  1
Elapsed:   2.7 ms

Best solution (rank 1)
  objective (maximize):  17
  soft violation score:  0
  item_a = 1
  item_b = 0
  item_c = 1
  item_d = 0

Hard constraints: 1 / 1 satisfied
Soft constraints: 0 violations
Optimality proven: yes

Elapsed is the service's own wall clock and varies from run to run. Add --json for the full SolveResult, --backend simulated_annealing to override the backend, or try validate, recommend, capabilities, example and export-schema. See docs/cli.md.

The problem JSON

The document behind the MCP and CLI examples above, the reduced form of examples/knapsack.json:

{
  "version": "1.0",
  "name": "knapsack",
  "variables": [
    {"name": "item_a", "type": "binary"},
    {"name": "item_b", "type": "binary"},
    {"name": "item_c", "type": "binary"},
    {"name": "item_d", "type": "binary"}
  ],
  "objective": {
    "direction": "maximize",
    "linear_terms": [
      {"variable": "item_a", "coefficient": 10},
      {"variable": "item_b", "coefficient": 8},
      {"variable": "item_c", "coefficient": 7},
      {"variable": "item_d", "coefficient": 6}
    ]
  },
  "constraints": [
    {
      "id": "capacity",
      "type": "hard",
      "terms": [
        {"variable": "item_a", "coefficient": 6},
        {"variable": "item_b", "coefficient": 5},
        {"variable": "item_c", "coefficient": 4},
        {"variable": "item_d", "coefficient": 3}
      ],
      "operator": "<=",
      "rhs": 10
    }
  ],
  "solver": {"backend": "exact"}
}

Integer variables ("type": "integer" with bounds, "version": "1.1"), cardinality constraints — exactly, at most or at least k of a set of binary variables, a hard at-most-one compiling without slack variables ("cardinality_constraints", "version": "1.2") — templates that write a large, regular model once over index sets and let the server expand it ("index_sets", "parameters", "variable_families" and the *_templates lists, "version": "1.3"), quadratic objective terms, soft constraints with weights and per-backend solver preferences are described in docs/problem-format.md. annealbridge export-schema prints the JSON Schema an agent can use for structured output.

Seven ready-to-run examples live in the repository — knapsack, assignment, TSP, integer knapsack, shift scheduling, exam timetabling (cardinality constraints) and TSP with templates (the TSP written once over index sets; annealbridge expand prints what it expands to). The installed package carries the same files: annealbridge example lists them and annealbridge example knapsack > knapsack.json saves one (or pipe it straight in with annealbridge example knapsack | annealbridge solve -); the MCP server serves the same seven documents as the resources under annealbridge://examples/.

How it works

The agent produces an OptimizationProblem: binary or bounded-integer variables, a linear or quadratic objective, and hard or soft linear and cardinality constraints. Nothing else. AnnealBridge then, deterministically:

  1. validates the problem and collects every error in one pass, after expanding any templates into explicit entries;

  2. compiles it into a BQM or a CQM, computing penalties, slack and integer encodings itself;

  3. solves it on a local or remote backend;

  4. re-validates every candidate against the original JSON, never trusting solver energy;

  5. ranks the feasible solutions and returns the top K with per-constraint evaluations.

An opt-in solver.postprocess step can also repair and locally improve the best samples in the original variables before ranking; what it produces is re-validated like any other candidate and marked by each solution's source. An optional solver.wall_clock_limit_seconds caps how long a solve on a local heuristic backend may take: when it runs out, the result holds what was completed, still re-validated and ranked, and says so (wall_clock_limit_reached). An MCP client that cancels a solve stops it rather than leaving it to run on.

The agent never writes a QUBO matrix, a penalty weight, a slack variable or an integer encoding, and every step is testable without an AI, a network or a vendor account.

Backends

Eight backends sit behind one protocol.

Backend

Kind

Path

Notes

exact

local

BQM

Enumerates every assignment; 24 compiled variables by default

simulated_annealing

local

BQM

Heuristic; the general-purpose choice, best of the three on small or hard-constrained problems; honours num_reads, num_sweeps, seed

tabu

local

BQM

Heuristic multistart tabu search, strong on dense QUBOs; the first choice once a dense problem is large; honours num_reads, seed

simulated_bifurcation

local

BQM

Heuristic dense-matrix dynamics (Goto et al. 2021), the choice for large dense unconstrained QUBOs, weaker on problems whose hard constraints compile to penalties; honours num_reads, num_sweeps, seed; optional CUDA via [gpu]

dwave_qpu

remote

BQM

D-Wave quantum annealer via EmbeddingComposite

leap_hybrid_bqm

remote

BQM

D-Wave Leap hybrid BQM solver

leap_hybrid_cqm

remote

CQM

D-Wave Leap hybrid CQM solver; native constraints

fujitsu_da

remote

BQM

Fujitsu Digital Annealer, QUBO API V4 over HTTPS, no SDK

Remote backends need their vendor credential and ANNEALBRIDGE_ALLOW_REMOTE=true; without both they report backend_unavailable. annealbridge recommend ranks the backends for a problem without solving it and never changes the one you asked for. Setup and per-backend behaviour: docs/backends.md.

Design guarantees

  • Business-level contract in both directions. Variables, objective and constraints in; ranked solutions with per-constraint evaluations out. No solver internals leak either way.

  • Two compiler paths. BQM (automatic penalties, binary slack, encoded integers) for annealers; CQM (native constraints and integers) for the Leap hybrid CQM solver. The backend chooses by declaring what it supports.

  • Bounded integers without exposure. "version": "1.1" adds integer variables with the encoding hidden; 1.0 behaviour is pinned by a golden test.

  • Counting rules said as such. "version": "1.2" adds cardinality constraints — one-hot, at most k, at least k over binary variables — and a hard at-most-one compiles to a pairwise penalty without slack variables; 1.0 and 1.1 behaviour is pinned by a compatibility golden.

  • Large models written once. "version": "1.3" adds index sets, parameter tables, variable families and templates, which the server expands into ordinary variables, terms and constraints before anything else; errors point back at the template, and a size ceiling refuses an oversized expansion whole instead of truncating it. 1.0–1.2 behaviour is pinned by the existing goldens.

  • Structured failures, never exceptions. Every outcome is a SolveResult with a status; every failure carries a stable error code with a recommended_action. infeasible is an answer, not a failure.

  • No silent decisions. An unavailable backend is reported, never swapped. An over-limit parameter is rejected, never clamped. An undeclared field is rejected, never ignored. Validator warnings travel with every solve result.

  • Safe by default. Remote execution and remote retries are off until enabled; every limit is an environment variable enforced as an error; vendor credentials are redacted from results, logs and error messages. The streamable-http transport has no authentication; keep it on a private network. See docs/security.md and SECURITY.md.

  • Enforced architecture. Import boundaries, "no backend names in the orchestration, validation or interface layers", and "a new backend plugs in without touching the pipeline" are tests, not conventions.

Documentation

The pages below live under docs/.

Page

What it covers

docs/problem-format.md

The input JSON: variables, objective, constraints, solver preferences

docs/output-format.md

SolveResult and every field it carries

docs/errors.md

Error catalog, warning codes, reason codes, exit codes

docs/cli.md

The annealbridge command line

docs/mcp.md

The MCP server: tools, prompts, resources, host configuration, Inspector

docs/backends.md

The eight backends, D-Wave and Fujitsu setup, adding a backend

docs/configuration.md

Every ANNEALBRIDGE_* variable and the vendor credentials

docs/architecture.md

Layers, package layout, design principles

docs/security.md

Defaults, limits, credential redaction, what reaches a vendor

docs/testing.md

Test layout, golden tests, live tests, CI

docs/limitations.md

Known limits and what is out of scope

Development

git clone https://github.com/TheTsungYing/AnnealBridge.git
cd AnnealBridge
pip install -e ".[all,dev]"
pytest

pytest runs the full suite with no skip and no xfail and never touches the network; the live vendor tests are opt-in (pytest -m remote). To install the development version without a checkout: pip install "annealbridge[all] @ git+https://github.com/TheTsungYing/AnnealBridge.git". Architecture rules, design principles and the pull-request checklist are in CONTRIBUTING.md.

Version 0.4.0: the problem contract (1.0 / 1.1 / 1.2 / 1.3), the eight backends, the CLI and the MCP tools are complete and covered by tests. What is not supported, by design for now, is listed in docs/limitations.md; changes are in CHANGELOG.md.

License

MIT

Available Tools

4 tools
get_optimization_capabilitiesA

Describe what this optimization server accepts and which solver backends are usable right now.

Call this when you need the supported problem vocabulary (variable types,
constraint operators, objective terms, accepted schema versions) or, per
backend, whether it is installed/configured (available), whether server
policy permits it (enabled), and its resource limits. It is not required
before every problem: for a small binary problem on a local backend the
example in the server instructions already shows the document shape. This
performs no solving and no network requests.

The full problem JSON schema is several times the size of everything
else, so problem_json_schema is null unless include_schema is true. Ask
for it when the document needs more than the example shows — integer
variables, soft constraints, solver preferences — or before inventing a
field; every field description is in it.

supported_variable_types lists the variable types a problem may declare —
"binary" and "integer" — and schema_versions lists every problem schema
version this server accepts, newest last. Integer variables are only
allowed when the problem carries "version": "1.1" at its top level;
"version": "1.0" accepts binary variables only.

Inputs: include_schema. Returns: Everything an agent needs before formulating and submitting a problem.

recommend_backendA

Rank the solver backends of this server for a given problem, without solving it.

Advisory only: solve_optimization always uses problem.solver.backend exactly as
given and never substitutes a backend. Each entry reports whether the backend is
usable right now (installed, credentialed, permitted by policy, within limits),
the model type it would compile to, deterministic reason codes, blocking errors,
and the same warnings validate_optimization_problem would give for that backend.
Based only on the problem structure, backend capabilities and server policy —
no cost estimation, no network requests, no quota consumed.

A problem with integer variables adds reason codes: R_INTEGER_NATIVE when the
backend compiles to cqm and takes integers as they are, R_INTEGER_ENCODED when
it compiles to bqm and must binary-encode them, and R_INTEGER_BLOWUP when that
encoding also raises an INTEGER_QUADRATIC_BLOWUP warning — a backend carrying
that code is ranked after the ones without it.

The entries are ordered best first, so the first usable entry is the default
choice when the user named no backend. Among backends of the same kind, two
reason codes come from a backend's declared, measured structural preference:
R_DENSE_STRENGTH when it declares that it reaches the same energy as its
peers in a fraction of the time on large dense unconstrained models and this
problem is one, R_PENALTY_WEAKNESS when it declares a lower hit rate on
models whose hard constraints compile to penalties and this problem has an
effective hard constraint. Both shapes are bqm-path shapes, so a backend that
compiles to cqm is never matched. A backend carrying the first is ranked
ahead of its neighbours, one carrying the second behind them; neither changes
which backends are usable.

Inputs: problem (required). Returns: Ranked backends for one problem (spec §23.2). ``valid`` is the problem's own va…

solve_optimizationA

Solve a structured binary or bounded-integer combinatorial optimization problem.

Use this when the user asks which items to take within a budget, weight or
capacity, how to assign people or jobs to seats, shifts or machines, in
which order to visit a handful of places, or how to split things into
groups or pick a subset that meets several requirements at once — anything
expressible as yes/no or bounded-count decisions with a linear or quadratic
score and linear rules, even when the user never says "optimization".

Call this only after translating the user's request into explicit binary or
bounded-integer variables, an objective (linear/quadratic, minimize or
maximize), and hard or soft linear constraints. Do not pass natural-language
requirements.

An integer variable is declared with "type": "integer" plus integer
lower_bound and upper_bound (both required), and the problem must then carry
"version": "1.1" at its top level. A backend that compiles to bqm encodes
each integer in binary, so the compiled size grows with the range of the
bounds; a backend that compiles to cqm takes integers natively. Integer
values come back as ints inside their declared bounds.

Inequality constraints (<=, >=) require integer coefficients and right-hand
sides. Soft constraint weights are in objective units.

Leave solver.penalty_multiplier at its default unless a previous result was
infeasible on a remote backend; hard constraint penalties are managed by the
server. Call validate_optimization_problem first when planning to use a
remote backend or when the problem is large; on a local backend an invalid
document comes back as status invalid_problem with the same errors and
recommended_action, so solving directly spends nothing. Use
get_optimization_capabilities when you need the backend list or the full
schema. Use recommend_backend to compare backends; the choice remains yours.

Returns ranked feasible solutions with per-constraint evaluations, or a
structured error with a recommended_action. When the status is infeasible,
read infeasibility for the candidate that came closest to feasibility and
the share of candidates each hard constraint rejected, so the answer can
name the binding requirement instead of only reporting failure. Whatever
the status, the result's warnings are the same advisory warnings
validate_optimization_problem gives for this backend (an ignored seed or
parameter, a wide integer range, a negligible soft weight, ...) followed
by any raised during the run; read them before trusting a weaker answer
than expected. A field the schema does not declare is a tool error naming
its path, never ignored. If the user did not name a backend, say in the
answer which backend ran and why.

Inputs: problem (required). Returns: The final outcome of solving an optimization problem.

validate_optimization_problemA

Check a structured optimization problem without solving it.

Returns semantic errors (each with a recommended_action), advisory
warnings, and an estimate of the compiled variable count including slack
bits. Call this before solve_optimization when planning to use a remote
backend, so problems can be fixed before spending quota, or when the
problem is large (many variables, wide integer ranges). On a local backend
solve_optimization can be called directly: an invalid document returns
status invalid_problem with the same errors and recommended_action.
Nothing is compiled or solved and no network requests are made.
solve_optimization reports the same warnings for the same backend, so
skipping this call never hides them; calling it first only saves the
solve.

A field the schema does not declare is a tool error naming its path,
never ignored: check the schema (get_optimization_capabilities with
include_schema: true returns it as problem_json_schema) before inventing
one.

The estimate follows the model type the chosen backend compiles to. On a
bqm backend it counts the slack bits of every inequality constraint plus
the binary-encoding bits of every integer variable, so a wider
lower_bound..upper_bound range costs more compiled variables. On a cqm
backend integer variables are native and no encoding bits are counted.

Inputs: problem (required). Returns: Full validation outcome (Phase 2 spec §20, 3a §9). ``valid`` is decided by ``er…

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.7/5.0

    Scored across 4 tools

    Disambiguation5/5

    Each tool has a clearly distinct role: validating, solving, querying capabilities, and ranking backends. Even though validate_optimization_problem and solve_optimization both report warnings, their purposes are explicitly separated and cross-referenced, so an agent should not confuse them.

    Naming Consistency5/5

    All tool names follow a consistent snake_case verb_noun pattern: validate_optimization_problem, recommend_backend, get_optimization_capabilities, solve_optimization. The verbs are descriptive and uniform in style.

    Tool Count5/5

    Four tools is a well-scoped set for this server's purpose: validate before solving, solve the main task, inspect capabilities, and get backend recommendations. Each tool earns its place without redundancy or bloat.

    Completeness5/5

    The tool surface covers the full workflow of an optimization server: understanding accepted problems, validating them, choosing a backend, and solving. No obvious dead ends or missing core operations are apparent for the stated domain.

    Maintenance

    ActivitySlowing
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      MCP-ORTools integrates Google's OR-Tools constraint programming solver with Large Language Models through the MCP, enabling AI models to: Submit and validate constraint models Set model parameters Solve constraint satisfaction and optimization problems Retrieve and analyze solution
      22
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables solving Constraint Satisfaction Problems (CSP) like N-Queens, graph coloring, and Sudoku, as well as Linear Programming optimization problems through both MCP tools and HTTP API endpoints.
      2
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables Claude Desktop and MCP-compatible agents to formulate, solve, and certify mathematical optimization problems using production-grade open-source solvers, providing mathematically grounded decisions.
      MIT