Expose deterministic multi-step tool flows as MCP tools to eliminate unnecessary LLM reasoning between steps.
Also known as dgenio/ChainWeaver
- Stars
- 6
- Tools
- 6
- Downloads, 30 days
- 117
- Latest version
- 0.12.1
- Last commit
- Nov 2, 2026
- License
- Apache-2.0
What is ChainWeaver MCP?
ChainWeaver exposes deterministic multi-step tool flows as MCP tools to eliminate unnecessary LLM reasoning between steps. It exposes 6 tools, such as passthrough, json_pluck, json_set.
Summary generated from the project's README
About ChainWeaver MCP server
Developers looking to reduce latency and costs in agentic workflows can use ChainWeaver to convert repeated tool sequences into single, deterministic capabilities. Instead of paying for an LLM to reason through every intermediate step of a predictable process, this server allows you to compile those steps into a governed flow that executes without model involvement between actions. It is designed for teams that have observed agent traces and identified patterns that no longer require semantic judgment.
Users implement this by wrapping functions as schema-validated Tools and wiring them into a Flow using the FlowRegistry and FlowExecutor. The system relies on Pydantic for strict I/O validation and provides structured audit traces for every step. It is a local execution layer that can be used standalone or as part of the Weaver Stack. It focuses on providing evidence for path promotion, detecting schema drift, and preserving security boundaries rather than acting as a general-purpose workflow engine.
What you can do with it
- 1Eliminate redundant model reasoningConvert a multi-turn process like searching, extracting, and validating facts into a single tool call that requires zero LLM involvement between steps.
- 2Identify repeatable agent patternsAnalyze existing agent traces to find candidate tool sequences that are frequently repeated and structurally safe to automate.
- 3Enforce strict data contractsEnsure that automated multi-step flows adhere to specific data structures using Pydantic validation at every stage.
Written from the project's README. Every use case is checked against a quote from it.
How to install ChainWeaver MCP
Formats verified 10 Nov 2026Add to CursorAdd to GooseInstall ChainWeaver MCP in Claude Code
$ claude mcp add chainweaver -- uvx chainweaverInstall ChainWeaver MCP in Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"chainweaver": {
"command": "uvx",
"args": [
"chainweaver"
]
}
}
}Install ChainWeaver MCP in VS Code
.vscode/mcp.json
{
"servers": {
"chainweaver": {
"type": "stdio",
"command": "uvx",
"args": [
"chainweaver"
]
}
}
}Install ChainWeaver MCP in VS Code CLI
$ code --add-mcp '{"name":"chainweaver","type":"stdio","command":"uvx","args":["chainweaver"]}'Install ChainWeaver MCP in Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"chainweaver": {
"command": "uvx",
"args": [
"chainweaver"
]
}
}
}Install ChainWeaver MCP in Codex
$ codex mcp add chainweaver -- uvx chainweaverInstall ChainWeaver MCP in Codex config.toml
~/.codex/config.toml
[mcp_servers.chainweaver] command = "uvx" args = ["chainweaver"]
Install ChainWeaver MCP in Gemini CLI
$ gemini mcp add -s user chainweaver uvx -- chainweaverInstall ChainWeaver MCP in Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"chainweaver": {
"command": "uvx",
"args": [
"chainweaver"
]
}
}
}ChainWeaver MCP tools 6
Detected from the READMEpassthroughjson_pluckjson_setassert_equalmap_listfilter_list
| passthrough | — | |
| json_pluck | — | |
| json_set | — | |
| assert_equal | — | |
| map_list | — | |
| filter_list | — |
Automated checks
Ran Nov 12, 2026Full report →Passed our automated checks. That is not a security audit: read the code and give the server the narrowest access it needs. How checks work
- Source repository linked and reachablePass
- Open source license (OSI)Pass
- Commit or release in the last yearPass
- Package name not close to a popular packagePass
- Remote endpoint uses HTTPSNot checked
- Destructive tools are labelledPass
- No hidden instructions to the modelPass
- No critical advisory in the package or its dependenciesPass
README
View on GitHubChainWeaver
Find where your agent no longer needs to reason. Review the evidence. Turn the accepted path into a governed deterministic capability.
Product thesis under validation — observe → prove → review → compile. ChainWeaver can inspect repeated tool behavior, surface candidates, and execute reviewed deterministic paths with typed contracts. Deterministic execution by itself is not the moat: if you already know the exact workflow, a normal Python function, LangGraph node, or provider-native tool may be simpler. The hypothesis being tested is that trace-derived evidence, useful rejection, governed promotion, security-boundary preservation, and drift detection make ChainWeaver worth adopting. See Product validation & adoption gates and #553.
Remove reasoning boundaries, never security boundaries. Compiling several tool calls into one capability must not silently aggregate privileges or erase child approval requirements. That invariant is tracked explicitly in #554.
Governance for deterministic tool paths. Typed I/O at every step, file-serializable flows, schema-drift detection, determinism attestation, property fuzzing, and structured audit traces provide a disciplined execution substrate for paths that have actually earned deterministic promotion.
Benchmarks are evidence about the executor, not proof of product-market fit. The repo's benchmark report is reproducible — regenerate it yourself with
python benchmarks/report.py— and shows the deterministic core avoiding model-mediated transitions in its synthetic comparison. It does not establish that every repeated path should be compiled, or that ChainWeaver beats the obvious plain-Python implementation. The independent validation program requires that manual baseline explicitly.
from chainweaver import Tool, Flow, FlowStep, FlowRegistry, FlowExecutor
# (NumberInput, ValueOutput, double_fn defined in full example below)
# 1. Wrap any function as a schema-validated Tool
double = Tool(name="double", description="Doubles a number.",
input_schema=NumberInput, output_schema=ValueOutput, fn=double_fn)
# 2. Wire tools into a Flow
flow = Flow(name="calc", description="Double a number.",
steps=[FlowStep(tool_name="double", input_mapping={"number": "number"})])
# 3. Register and execute — zero LLM calls
registry = FlowRegistry()
registry.register_flow(flow)
executor = FlowExecutor(registry=registry)
executor.register_tool(double)
result = executor.execute_flow("calc", {"number": 5})
# result.final_output → {"number": 5, "value": 10}
See the full example below or run
python examples/simple_linear_flow.py
Installation · Why ChainWeaver? · Is this for me? · Product validation · Quick Start · Architecture · Docs site · Roadmap
See it in 30 seconds
The deterministic executor solves a simple problem: once a path has been shown to need no intermediate reasoning, stop paying a model to re-decide the same plumbing on every run.
Before — a model-mediated path:
turn 1 ─► LLM("plan") ─► search(query) ─► 12 results
turn 2 ─► LLM("next?") ─► extract(results) ─► 8 facts
turn 3 ─► LLM("next?") ─► validate(facts) ─► 7 facts
turn 4 ─► LLM("next?") ─► format(facts) ─► answer
After review — the accepted path can run deterministically:
turn 1 ─► LLM("plan") ─► search_summarize_flow(query)
└─ search ─► extract ─► validate ─► format
The agent still decides which capability to invoke. The deterministic steps inside it run with strict Pydantic validation and no LLM involvement.
The harder product question comes before this diagram: should this path be compiled at all? A useful ChainWeaver analysis must be able to show why a candidate is recurrent and structurally safe and reject paths where semantic judgment, side effects, authorization, or approval boundaries still matter. That claim is currently being tested on independent traces in #553.
Copy-paste executor path:
pip install 'chainweaver[yaml]'
python examples/simple_linear_flow.py
The summary below is a condensed view of the real ExecutionResult the script
produces:
flow=double_add_format success=True
final_output={'number': 5, 'value': 20, 'result': 'Final value: 20'}
step 0 double {'value': 10}
step 1 add_ten {'value': 20}
step 2 format_result {'result': 'Final value: 20'}
Why ChainWeaver?
Why not just write a Python function?
Often, you should.
If your team already knows the workflow is fixed, a normal function or the workflow primitives in your existing framework are usually the lowest-complexity answer. ChainWeaver should earn another dependency only when its lifecycle adds meaningful value—for example:
- discovering non-obvious repeated model-mediated paths from real traces;
- showing evidence for recurrence, dataflow compatibility, and counterexamples;
- rejecting tempting paths that still require semantic judgment;
- preserving approval and authorization constraints during promotion;
- producing reproducible review evidence and artifact identity;
- detecting schema/safety/policy drift after promotion;
- exporting or executing the accepted capability without pretending that fewer model calls automatically means greater correctness.
Whether those advantages are strong enough in real teams is a falsifiable product hypothesis, not a README assumption. See docs/product-validation.md.
When an LLM-powered agent routes tools together — fetch_data → transform → store — a
common pattern is to insert an LLM call between steps so the model can decide
what to do next. For a path that has been demonstrated and reviewed as fully
deterministic, those intermediate calls can add latency, cost, and variability
without adding useful judgment.
ChainWeaver's executor can run an accepted deterministic path without any LLM involvement between steps:
User request
│
▼
FlowExecutor ──► Tool A ──► Tool B ──► Tool C
│
▼
Response
| Criterion | Model-mediated path | ChainWeaver deterministic path |
|---|---|---|
| LLM calls between deterministic steps | potentially one or more | 0 |
| Reproducibility | depends on model decisions | deterministic path |
| Schema validation | framework/application dependent | Pydantic enforced |
| Observability | framework/application dependent | structured step logs |
| Reusability | application dependent | registered, versioned flows |
How is this different from LangChain / LangGraph / Prefect / Dagster / Temporal?
Those frameworks can also execute deterministic code. ChainWeaver should not be selected because deterministic execution is impossible elsewhere. Its current product thesis is narrower: start from observed agent/tool behavior, establish which regions no longer need reasoning, make the evidence and rejections reviewable, then promote accepted paths into governed deterministic capabilities.
The execution substrate remains deliberately small and LLM-free between steps, but the project is testing whether the evidence/governance lifecycle—not the mere existence of another workflow runtime—is the part users value.
See docs/comparisons.md for the detailed, versioned comparison and docs/product-validation.md for the criteria that can falsify this positioning.
Is this for me?
ChainWeaver is built for one specific shape of problem. The full fit/non-fit page covers the nuances; the short version:
Use ChainWeaver when
- You have real agent/tool traces and suspect parts of the path are repeated plumbing rather than useful model judgment.
- You want evidence and review around which paths deserve deterministic promotion, not only a runtime for a workflow you already know.
- Determinism, strict schemas, auditability, and drift detection matter once a path is promoted.
- You are prepared to keep security and approval boundaries explicit rather than treating a macro-tool invocation as blanket child authorization.
Don't use ChainWeaver when
- You already know the workflow and a normal Python function or your existing framework expresses it clearly enough.
- Every step requires open-ended reasoning to pick the next one (use an agent framework: LangGraph, the OpenAI / Anthropic SDK tool-use loops).
- You need a general workflow engine for scheduled / durable jobs across time (use Prefect, Dagster, or Temporal).
- You expect the executor to call an LLM. It deliberately doesn't.
- You cannot preserve the authorization/approval semantics of a side-effecting path during compilation.
The product thesis, validation protocol, and kill/pivot criteria are public in docs/product-validation.md.
For the correctness argument behind the deterministic execution design, see docs/data-integrity.md.
Part of the Weaver Stack
ChainWeaver is the deterministic multi-step tool execution layer of the
Weaver Stack — a family of small,
composable SDKs that share weaver-spec's SelectableItem routing contract.
On the request path a router picks which capability to invoke, ChainWeaver
runs the deterministic tool path behind it, and downstream layers gate and
guard the call:
flowchart LR
req([Request]) --> ctx[contextweaver<br/>context assembly]
ctx --> cw[<b>ChainWeaver</b><br/>deterministic flow execution]
cw --> ak[agent-kernel<br/>capability gating]
ak --> af[agentfence<br/>runtime guardrails]
subgraph adjacent [Adjacent · use any subset]
vg[vibeguard]
lw[lessonweaver]
se[skdr-eval]
end
Use standalone or together. Each layer stands on its own — ChainWeaver's
base install has no hard dependency on any sibling and works fully
standalone. Real interop runs through the chainweaver[weaver-stack] extra,
which pins the published weaver-contracts
package: ChainWeaver consumes its SelectableItem / RoutingDecision /
CapabilityToken types directly, so a router can hand a routing decision
straight to resolve_flow_from_routing_decision() for deterministic
execution. See the runnable
Weaver Stack golden path (issue #234).
| Layer | What it owns | Sibling project |
|---|---|---|
| Routing / capability selection | "Which named operation handles this request?" | weaver-spec (#91 — SelectableItem contract) |
| Context assembly | "What facts and tool descriptions belong in the prompt?" | contextweaver (#106) |
| Agent kernel | The model-mediated tool-use loop itself | agent-kernel (#89) |
| Deterministic flow execution | "Run this exact tool sequence with strict schemas, no LLM between steps" | ChainWeaver — this repo |
| Lessons & evaluation | Turning traces into reviewed operational guidance (how ChainWeaver feeds it) | lessonweaver (#210) |
ChainWeaver does not replace an agent framework. It is meant to be called from one — see the LangGraph recipe (issue #205) and the OpenAI Agents SDK recipe (issue #206) for the canonical integration patterns.
For host-level expectations (when to invoke, how to store traces, side-effect tools, MCP parity), see the Runtime responsibilities page.
Installation
pip install chainweaver # base install — no extras
pip install 'chainweaver[yaml]' # most common — needed for .flow.yaml files
pip install 'chainweaver[yaml,otel,mcp]' # combine extras with commas
The base install pulls only five runtime dependencies (deepdiff,
packaging, pydantic, tenacity, typer) and has no transitive LLM
SDK pinned. Pick extras for the integrations you actually use:
| Extra | Use when | Pulls in |
|---|---|---|
chainweaver[yaml] |
Reading / writing .flow.yaml flow files (the CLI's run, validate, check, doctor commands need this) |
pyyaml |
chainweaver[otel] |
Emitting OpenTelemetry spans for every flow run | opentelemetry-api |
chainweaver[mcp] |
Exposing flows over MCP via the chainweaver.mcp adapter |
mcp |
chainweaver[contrib] |
Importing the curated standard tool library (see Standard tool library) | (no extra deps today) |
chainweaver[langchain] |
Bidirectional adapters between ChainWeaver and LangChain BaseTool |
langchain-core |
chainweaver[llamaindex] |
Bidirectional adapters between ChainWeaver and LlamaIndex FunctionTool |
llama-index-core |
chainweaver[test] |
Hypothesis-based property tests for your own flows | hypothesis, hypothesis-jsonschema |
chainweaver[docs] |
Building the docs site locally with mkdocs | mkdocs, mkdocs-material, mkdocstrings |
chainweaver[weaver-stack] |
Real Weaver Stack interop — consuming the shared routing/capability contract (weaver-spec #91, contextweaver #106, agent-kernel #89, #233) |
weaver-contracts |
chainweaver[integrations] |
Every integration extra above at once — the composition CI exercises | the union of the integration rows above |
Maintainer tooling (pytest, ruff, mypy, nbmake, ...) is not a published
extra: it lives in PEP 735 dependency groups, installed with
pip install -e ".[integrations]" --group dev (#550). The [dev] extra no
longer exists.
Package metadata (pyproject.toml) publishes URLs for the
documentation, the
source, the
changelog,
and the
issue tracker, so pip show chainweaver and the PyPI sidebar point users to the right place.
Quick Start
Define tools, build a flow, and execute it
from pydantic import BaseModel
from chainweaver import Tool, Flow, FlowStep, FlowRegistry, FlowExecutor
# --- 1. Declare schemas ---
class NumberInput(BaseModel):
number: int
class ValueOutput(BaseModel):
value: int
class ValueInput(BaseModel):
value: int
class FormattedOutput(BaseModel):
result: str
# --- 2. Implement tool functions ---
def double_fn(inp: NumberInput) -> dict:
return {"value": inp.number * 2}
def add_ten_fn(inp: ValueInput) -> dict:
return {"value": inp.value + 10}
def format_result_fn(inp: ValueInput) -> dict:
return {"result": f"Final value: {inp.value}"}
# --- 3. Wrap as Tool objects ---
double_tool = Tool(
name="double",
description="Takes a number and returns its double.",
input_schema=NumberInput,
output_schema=ValueOutput,
fn=double_fn,
)
add_ten_tool = Tool(
name="add_ten",
description="Takes a value and returns value + 10.",
input_schema=ValueInput,
output_schema=ValueOutput,
fn=add_ten_fn,
)
format_tool = Tool(
name="format_result",
description="Formats a numeric value into a human-readable string.",
input_schema=ValueInput,
output_schema=FormattedOutput,
fn=format_result_fn,
)
# --- 4. Define the flow ---
flow = Flow(
name="double_add_format",
description="Doubles a number, adds 10, and formats the result.",
steps=[
FlowStep(tool_name="double", input_mapping={"number": "number"}),
FlowStep(tool_name="add_ten", input_mapping={"value": "value"}),
FlowStep(tool_name="format_result", input_mapping={"value": "value"}),
],
)
# --- 5. Execute ---
registry = FlowRegistry()
registry.register_flow(flow)
executor = FlowExecutor(registry=registry)
executor.register_tool(double_tool)
executor.register_tool(add_ten_tool)
executor.register_tool(format_tool)
result = executor.execute_flow("double_add_format", {"number": 5})
print(result.success) # True
print(result.final_output) # {'number': 5, 'value': 20, 'result': 'Final value: 20'}
for record in result.execution_log:
print(record.step_index, record.tool_name, record.outputs)
# 0 double {'value': 10}
# 1 add_ten {'value': 20}
# 2 format_result {'result': 'Final value: 20'}
You can also run the bundled examples directly:
python examples/simple_linear_flow.py # simple arithmetic flow
python examples/etl_flow.py # ETL flow: fetch → validate → normalize → enrich → store
python examples/mcp_search_flow.py # MCP-style search → extract → format flow
python examples/naive_vs_compiled.py # timing comparison: naive LLM calls vs ChainWeaver flow
python examples/coding_agent_pr_review.py # deterministic PR-review checklist
python examples/coding_agent_changelog.py # changelog generation workflow template
python examples/coding_agent_debug_log.py # debug-log triage workflow template
python examples/mcp_style_before_after_demo.py # before/after MCP-style flow demo
python examples/release_readiness_flow/release_readiness.py # deterministic release-readiness gate
python examples/skdr_policy_eval_flow.py # offline policy-evaluation workflow template
python examples/integrations/langgraph_node.py # call a flow from a LangGraph node (needs chainweaver[langgraph])
python examples/integrations/openai_agents_tool.py # expose a flow as an OpenAI Agents SDK tool (needs chainweaver[openai-agents])
The hosted docs also include a cookbook with paired
scripts under examples/cookbook/, plus framework recipes and workflow
templates (LangGraph, OpenAI Agents SDK, release-readiness, policy evaluation).
With the @tool decorator
The @tool decorator eliminates boilerplate by introspecting type hints to
auto-generate input schemas:
from pydantic import BaseModel
from chainweaver import tool, Flow, FlowStep, FlowRegistry, FlowExecutor
class ValueOutput(BaseModel):
value: int
class FormattedOutput(BaseModel):
result: str
@tool(description="Doubles a number.")
def double(number: int) -> ValueOutput:
return {"value": number * 2}
@tool(description="Adds ten.")
def add_ten(value: int) -> ValueOutput:
return {"value": value + 10}
@tool(description="Formats the result.")
def format_result(value: int) -> FormattedOutput:
return {"result": f"Final value: {value}"}
flow = Flow(
name="double_add_format",
description="Doubles a number, adds 10, and formats.",
steps=[
FlowStep(tool_name="double", input_mapping={"number": "number"}),
FlowStep(tool_name="add_ten", input_mapping={"value": "value"}),
FlowStep(tool_name="format_result", input_mapping={"value": "value"}),
],
)
registry = FlowRegistry()
registry.register_flow(flow)
executor = FlowExecutor(registry=registry)
executor.register_tool(double)
executor.register_tool(add_ten)
executor.register_tool(format_result)
result = executor.execute_flow("double_add_format", {"number": 5})
print(result.final_output) # {'number': 5, 'value': 20, 'result': 'Final value: 20'}
Decorated tools are also directly callable:
print(double(number=5)) # {'value': 10}
See examples/decorator_tool.py for a runnable before/after comparison.
With FlowBuilder
FlowBuilder provides a fluent, chainable API as a more Pythonic alternative
to constructing Flow objects directly. It produces an identical Flow — it
is syntax sugar, not a replacement:
from chainweaver import FlowBuilder
flow = (
FlowBuilder("double_add_format", "Doubles a number, adds 10, and formats.")
.step("double", number="number")
.step("add_ten", value="value")
.step("format_result", value="value")
.build()
)
.step(tool_name, **mapping)— adds a step; string values are context-key lookups, non-string values are literal constants, no kwargs = full-context passthrough..step_from(flow_step)— appends a pre-builtFlowStepfor interop..with_input_schema(Model)/.with_output_schema(Model)— optional flow-level Pydantic schema declarations..with_trigger(conditions)— optional free-form trigger metadata..build()— returns a validatedFlow; raisesFlowBuilderErrorifnameordescriptionis missing.
Interactive playground
Want to try ChainWeaver without installing anything locally? The
playground/ directory ships a Streamlit app that lets you pick
a pre-loaded flow, edit its JSON input, run it, and watch the step-by-step,
LLM-free execution trace with a Mermaid diagram — the same FlowExecutor
the library ships.
pip install -r playground/requirements.txt
streamlit run playground/app.py
It ships three example flows (arithmetic, a data flow, and an MCP-style
search), produces shareable ?share=<token> links that round-trip a run through
the URL, and is fully stateless so it deploys to Streamlit Community Cloud with
no backend. See playground/README.md for local-run and
deployment instructions.
Architecture
chainweaver/
├── __init__.py # Public API
├── builder.py # FlowBuilder — fluent API for flow construction
├── compat.py # schema_fingerprint, check_flow_compatibility
├── compiler.py # compile_flow — static schema flow validation
├── decorators.py # @tool decorator for zero-boilerplate tool definition
├── tools.py # Tool — named callable with Pydantic schemas
├── flow.py # FlowStep + Flow + FlowStatus — ordered step definitions
├── registry.py # FlowRegistry — multi-version flow catalogue
├── executor.py # FlowExecutor — deterministic, LLM-free runner
├── exceptions.py # Typed exceptions with traceable context
└── log_utils.py # Structured per-step logging
Core abstractions
Tool
Tool(
name="my_tool",
description="...",
input_schema=MyInputModel, # Pydantic BaseModel
output_schema=MyOutputModel, # Pydantic BaseModel
fn=my_callable,
)
A tool wraps a plain Python callable together with Pydantic models for strict input/output validation.
ChainWeaver MCP questions
How do I add ChainWeaver MCP to Claude Code?
Run claude mcp add chainweaver -- uvx chainweaver in your terminal. Add --scope user to make it available in every project.
How do I add ChainWeaver MCP to Cursor?
Open ~/.cursor/mcp.json and add the server under mcpServers, using the Cursor config shown in the install section above.
What tools does ChainWeaver MCP provide?
It exposes 6 tools, including passthrough, json_pluck, json_set, assert_equal, map_list.
How does ChainWeaver differ from LangChain or LangGraph?
While those frameworks can execute deterministic code, ChainWeaver focuses on identifying repeated model-mediated paths from traces and promoting them to governed, deterministic capabilities.
Can I use ChainWeaver if I already have a fixed workflow?
If you already know the workflow is fixed, a normal Python function or existing framework primitives are usually the lowest-complexity answer; ChainWeaver is intended for when you need lifecycle value like drift detection and reviewable evidence.