MCP server¶
Expose LazyTools' project and coding tools to Claude Code, Codex or another MCP host. Engine-backed write/review tools are synchronous; detached work and durable approval tickets belong to the async code bridge. Other connectors support data, reports and communication. The MCP connector is the reverse direction: it imports another server's tools into an agent.
LazyTools 0.18.0 is Alpha. The [mcp] extra accepts the official MCP Python SDK 1.x and 2.x (mcp>=1.0,<3). Install the coding runtime dependencies too:
python -m pip install "lazytoolkit[engines,mcp] @ git+https://github.com/selvaz/LazyTools.git@v0.18.0"
Install the assistant skills¶
After installing LazyTools with the mcp extra and LazyBridge 1.12.0 or newer,
run these three commands to install both skills and register the read-only
server in Claude Code:
python -m lazybridge.skill install
python -m lazytools.skill install
claude mcp add --transport stdio lazytools -- lazytools-mcp
The installers also target Codex when its home exists; see the MCP setup for persistent project state and write access. Rerun the installers after upgrades.
For Codex, add [mcp_servers.lazytools] with command = "lazytools-mcp"
to ~/.codex/config.toml. Restart the host after changing its configuration.
Collaboration setup¶
From your workspace root, save lazytools.json with local paths:
Then launch the same provider combination linked from the homepage:
lazytools-mcp projects code_review claude_review code_write code_sessions --allow-unsafe --config lazytools.json
code_root confines repository/cwd arguments; Claude Bash is not path-confined.
projects_store_db makes state durable; without config or the Store env vars,
Projects uses memory. Core project tools are on by default. For contracts and
verification tools, set LAZYTOOLS_PROJECTS_TOOLS=full in the server environment.
The optional code_bridge_db, code_bridge_registry_db, and knowledge_db keys
set LAZYTOOLS_CODE_BRIDGE_DB, LAZYTOOLS_CODE_BRIDGE_REGISTRY_DB, and
LAZYTOOLS_KNOWLEDGE_DB respectively for providers and child processes. An explicit
config key overrides the caller's environment; an omitted key leaves it unchanged.
The optional dispatch_launch_mode key sets the dispatcher launch mode to auto,
governed, or legacy; when omitted, the dispatcher's default applies.
Sign in to the local coding runtimes; with a subscription login their turns use
plan quota. Authentication can also follow another runtime-configured billing
path. Coding providers require explicit selection and --allow-unsafe.
A stdio host can launch the server using this configuration (the host's working directory must be the intended workspace, or replace the config with an absolute path). The executable must be available in that host's environment:
{
"mcpServers": {
"lazytools": {
"command": "lazytools-mcp",
"args": ["projects", "code_review", "claude_review", "code_write", "code_sessions",
"--allow-unsafe", "--config", "lazytools.json"],
"env": {"LAZYTOOLS_PROJECTS_TOOLS": "full"}
}
}
}
--allow-unsafe enables writes without an interactive confirmation gate. It
is separate from the bridge's durable approvals. Select only the providers
needed. MCP calls block for the delegated turn; configure host timeouts or
use detached bridge jobs. See code support for
Claude-writes/Codex-reviews calls and session_name aliases.
For a persistent server, --http --host 127.0.0.1 --port 8787 serves Streamable
HTTP at /mcp; a compatible host uses a type: "http" entry and that URL.
The default transport is stdio and logs go to stderr.
The bridge is thin because LazyBridge already normalises every tool behind
one abstraction: tool.definition() yields the JSON Schema MCP wants for
inputSchema, and await tool.run(**kwargs) dispatches with argument
validation built in. The whole server is expand providers → list them →
dispatch calls.
Quick start¶
Run it over stdio (the transport MCP hosts launch):
lazytools-mcp # all read-only providers
lazytools-mcp datahub statistical # a subset (positional provider ids)
python -m lazytools.mcp_server # equivalent module form
Point Claude Desktop / Claude Code at it:
That's it — the host now sees LazyTools' read-only surface as native tools.
Providers whose optional extra is missing are simply skipped, a bare
[mcp] install serves available core providers such as registry/projects/report.
datahub and statistical additionally need the separately installed hub; install
lazystats[regimes] / the [web] extra to light up regimes / web.
Orchestration server¶
lazytools-orchestration-mcp runs the same server with only the orchestration
providers: code_bridge, code_review, claude_review, code_sessions,
codemap, projects, fleet, dispatch, knowledge and pr. code_write and the data providers are never
mounted. See the design spec.
lazytools-orchestration-mcp --list-tools
lazytools-orchestration-mcp --allow-unsafe --config lazytools.json
It takes the same flags and environment variables as lazytools-mcp. Positional
ids (or LAZYTOOLS_MCP_PROVIDERS) narrow the selection; an id outside the list
above is an error and the server does not start.
Without --allow-unsafe it serves the codemap, fleet, lessons_search,
pr_watch_poll and read-only projects tools. With it, bridge jobs, ticket
decisions and cancellation, pull-request work, reviews, named sessions, project writes and lessons_record are added. It starts with one coding CLI installed or none: the review
provider of a missing CLI is skipped with a warning (Codex is also found through
CODEX_BIN or the desktop app), and no engine SDK is imported at start.
On either server, --list-tools prints the names of the tools the same flags
would serve, one per line, and exits without starting a transport.
Deprecation. lazytools-mcp keeps the coding providers (code_bridge,
code_review, claude_review, code_sessions, codemap, fleet, pr) for one
release and logs a note to stderr when it mounts any of them. Move those entries
of your host configuration to lazytools-orchestration-mcp.
Providers¶
lazytools-mcp serves the available read-only providers by default. Coding
and specialist-agent providers require explicit selection and opt-in. Pass ids to select a
subset, or set LAZYTOOLS_MCP_PROVIDERS=datahub,statistical in the env.
| id | Provider | Tools | Needs |
|---|---|---|---|
registry |
RegistryTools() |
registry_status, artifact_search, artifact_get (+ artifact_register with --allow-unsafe) |
none (core) |
datahub |
DataHubTools() |
datahub_* discovery, resolution, financial facts |
market-data-hub installed |
statistical |
StatisticalAnalysisTools() |
volatility, correlation, outliers, regression | market-data-hub installed |
regimes |
RegimeTools() |
regime_* read-only inspection |
lazystats[regimes] |
web |
WebTools() |
search / crawl / get-page | [web] extra |
fin |
PortfolioOptimizationTools() + PortfolioTreeTools() |
portfolio_optimizer_* (flat node) + portfolio_tree_* (multi-node, interoperable with LazyPortfolio's Tree Studio) |
lazyfin, lazyportfolio |
optimizer_agent |
optimizer_specialist(...) — a lazybridge.Agent |
one tool, portfolio-optimizer-specialist(task: str) |
--allow-unsafe + DEEPSEEK_API_KEY (opt-in only, see below) |
report_agent |
report_specialist(...) — a lazybridge.Agent |
one tool, report-specialist(task: str) |
--allow-unsafe + DEEPSEEK_API_KEY (opt-in only, see below) |
projects |
ProjectsTools() |
records, owner, plans, schedule/Gantt, quota, notes, cost; full profile adds contracts/verification | configured Store for persistence; writes need --allow-unsafe |
code_write |
CodeWriteTools(...) |
codex_write, claude_code_write |
--allow-unsafe, local runtimes; Claude needs [engines] |
code_sessions |
CodeSessionTools(...) |
list/bind/rename/forget native aliases | explicit opt-in with --allow-unsafe |
code_bridge |
CodeBridgeTools(...) |
code_bridge_submit, code_bridge_status, code_bridge_result — local and cloud coding jobs through lazytools-code-bridge |
--allow-unsafe; cloud jobs also need allow_cloud=true per call |
fleet |
FleetTools(...) |
bridge_jobs, bridge_pending, bridge_route, bridge_autonomy, bridge_models, capabilities_search, bridge_events (+ bridge_approve, bridge_reject, bridge_cancel with --allow-unsafe) |
none |
dispatch |
DispatchTools(...) |
dispatch_status, dispatch_wait (+ dispatch_start, dispatch_stop with --allow-unsafe) |
file-backed projects store |
knowledge |
KnowledgeTools(...) |
lessons_search (+ lessons_record with --allow-unsafe) — the dispatcher's lessons store |
none (core) |
pr |
PrTools(...) |
pr_watch_poll (+ pr_navigate, bridge_publish, bridge_apply with --allow-unsafe) |
gh CLI, authenticated |
code_review |
codex_reviewer(...), codex_consultant(...), codex_native_reviewer(...) — Tools that delegate through CodexEngine |
codex_code_review, codex_ask, codex_review_changes |
--allow-unsafe + a locally authenticated codex CLI (opt-in only, see below) |
claude_review |
claude_reviewer(...), claude_consultant(...) — Tools that delegate through ClaudeCodeEngine |
claude_code_review, claude_ask |
--allow-unsafe + a locally authenticated claude CLI (opt-in only) |
studio |
Published agents and pipelines discovered from LazyStudio | each published studio_<slug> tool, studio_run_status; studio_status when disconnected |
LazyStudio operator token; published calls need --allow-unsafe |
Use Studio agents from Claude Code / Codex¶
LazyStudio agents and pipelines marked as MCP-exposed can be discovered when
the server starts and called through the studio provider. Set the Studio URL
and operator-token path if you do not use their defaults:
export LAZYSTUDIO_URL=http://127.0.0.1:8000
export LAZYSTUDIO_TOKEN_FILE=~/.lazystudio/operator-token
lazytools-mcp studio --allow-unsafe
The defaults are the values above. --allow-unsafe is intentional: invoking a
published tool runs an agent and may have side effects, so the provider follows
the same provider-level opt-in used by other write-capable tools. Without the
flag, only studio_run_status is exposed. If Studio is down or its token is
missing, the MCP server still starts and exposes studio_run_status plus
studio_status, which explains how to repair the connection. Restart the MCP
server after publishing or unpublishing a tool so it refreshes the tool list.
To let Claude Code spawn the stdio server:
For Codex, add an equivalent stdio MCP server entry to ~/.codex/config.toml:
Each published tool accepts one task string. A run that finishes during the
Studio wait window returns its output directly. A longer run returns
still running, run_id=...; pass that id to studio_run_status(run_id).
web — keep interactive research out of the production news DB¶
By default the web provider uses LAZYCRAWLER_NEWS_DB for everything,
read and write: this is what scheduled production agents rely on, and it is
unchanged when the variable below is unset. An interactive session (Claude
Code through the workspace .mcp.json, one-off research) should not share that
store: its pages land in the same pages/sessions tables with nothing marking
them as interactive, and its writes contend with the scheduled crawl's lock
(database is locked). Set LAZYTOOLS_WEB_CACHE_DB to isolate it:
LAZYTOOLS_WEB_CACHE_DB |
Effect |
|---|---|
| unset | Today's behaviour: the crawler reads and writes LAZYCRAWLER_NEWS_DB. |
| a file path | web_search, web_crawl, web_crawl_many write to that SQLite file (created on demand, with its directory; safe to delete). |
empty or default |
Same, at ~/.lazytools/web_cache.sqlite (LAZYTOOLS_DATA_DIR replaces ~/.lazytools). |
none (or :memory:) |
Nothing on disk: pages live in process memory and vanish on exit. |
When it is set, LAZYCRAWLER_NEWS_DB (if it names an existing file) is opened
read-only (SQLite mode=ro: no writes, no WAL pragma, no migrations) and the
read tools merge the two stores. There is no write-through and no copying:
| Tool | Reads |
|---|---|
get_page |
the interactive row if present, else the production row |
get_session_pages, get_crawl_graph |
the interactive store if it has rows for that session, else production |
get_artifacts, get_rag_document |
the one store that owns the page (or session): interactive if it holds it, even with no artifacts, else production. A newer interactive copy of a URL never inherits the production copy's tables or images |
search_cached |
interactive hits first, then production hits, de-duplicated by page, cut to limit |
get_cache_stats |
{"interactive": {...}, "production": {...} or null} instead of flat counts |
The fetch tools do not reuse production pages as a fetch cache (they only know
the interactive store), so a URL already in news.db is fetched again.
Guard. If the cache path is the same file as LAZYCRAWLER_NEWS_DB (or its
-wal/-shm/-journal side files), or lies anywhere under
C:\ProgramData\InvestmentCommittee, the provider raises WebCachePathError
and the server refuses to start: this error is not downgraded to a skipped
provider. The guard only runs when LAZYTOOLS_WEB_CACHE_DB is set.
Enable it for interactive use by adding the variable to the workspace
.mcp.json server env (never to the production project.toml env):
{
"mcpServers": {
"lazytools": {
"command": "lazytools-mcp",
"args": ["web"],
"env": {
"LAZYCRAWLER_NEWS_DB": "C:\\ProgramData\\InvestmentCommittee\\live\\db\\news.db",
"LAZYTOOLS_WEB_CACHE_DB": "default"
}
}
}
}
.mcp.json variables relevant to web: LAZYCRAWLER_NEWS_DB (production store,
read-only once isolation is on), LAZYTOOLS_WEB_CACHE_DB (this section),
LAZYTOOLS_WEB_MODEL (smart-mode extraction model, default deepseek-v4-flash),
LAZYTOOLS_DATA_DIR (base of the default cache path). --config accepts
web_cache_db (same values) and news_db_path for the same two settings.
optimizer_agent/report_agent are two providers that construct a real
lazybridge.Agent instead of a deterministic ToolProvider — calling their
tool runs a live LLM-driven loop (its own internal tool calls) and returns
only the final text. Like coding providers, they are never
served in the default read-only surface, and won't construct even with
--allow-unsafe unless the configured model's API key is set (default model
deepseek-v4-flash, override with LAZYTOOLS_OPTIMIZER_AGENT_MODEL /
LAZYTOOLS_REPORT_AGENT_MODEL).
code_review — hand a review to Codex¶
code_review is the same idea pointed at your own repositories:
lazybridge.Agents whose engine is
CodexEngine
— JSON-RPC to the locally authenticated codex app-server, inheriting its runtime authentication — served as three tools:
codex_code_review(task, repo_path=None, diff_ref=None, paths=None, thread_id=None, session_name=None, model=None, effort=None) -> str
codex_ask(question, repo_path=None, thread_id=None, session_name=None, model=None, effort=None) -> str
codex_review_changes(repo_path=None, scope="uncommitted", ref=None, session_name=None, model=None, effort=None) -> str
codex_code_review finds defects in code you point it at; codex_ask answers a
design question about it ("does this protocol support X", "what breaks if I
change Y"); codex_review_changes runs Codex' own review harness over a typed
target (uncommitted / branch + ref / commit + ref) with no instructions
from us at all. The split is not cosmetic: the reviewer's instructions turn
every question into a findings list, and the native harness cannot be steered
because the protocol has no prompt slot for it.
Every Codex tool takes per-call model / effort overrides ("same question,
stronger model" is a legitimate consulting move; the env-var settings below
remain the defaults). effort is checked: one of none, minimal, low,
medium, high, xhigh, max, ultra, else a ValueError lists them. The consultant
differs from the reviewers in one more way: it carries the server's own read-only LazyTools toolset as Codex
dynamic tools — the web, datahub, statistical, fin and
econ_calendar providers, built from the same factories and configuration
the MCP server serves, so a consultant that searches the web or runs the
optimizer hits the same databases and caches as the equivalent MCP tools.
(Dynamic tools ride the app-server channel and need no MCP registration on
the participant's side — a Codex thread reaching this server through its own
config.toml MCP entry gets rejected by approval_policy="never" before
execution, which is exactly the path this avoids.) The reviewers get the
web too (since 2026-08-19 — a review can need to check a CVE or whether an
API is really deprecated), but not the LazyTools toolset: a reviewer reads
code, it does not run the optimizer.
Codex reads the files and runs git itself, so a call is "point it at a
repository and say what to look at":
Follow-ups reuse native history. Every reply's header carries thread_id=<id>; pass it
back and the next call continues the same Codex thread, which still holds what
it read and concluded, instead of re-exploring the repository from scratch:
Threads are durable (they live in the Codex CLI's own session store), so this works across calls and across processes — but a thread belongs to the repository it was opened on; don't reuse one against a different repo.
Or name the conversation. Pass session_name="notes" on any of these tools
and the thread is remembered under that alias (per repository, in LazyBridge's
SessionRegistry file): the first call opens it, later calls with the same name
resume it, and no id needs carrying. An explicit thread_id still wins and
re-points the name at it. The header then reads
thread_id=<id> session_name=notes.
It runs in Codex' read-only sandbox (approval_policy="never", so nothing
can block the non-interactive transport): it reports, it never patches. Like
the other agent providers it is opt-in (--allow-unsafe) because a call spends
a real model turn; it is skipped entirely when the codex CLI can't be found.
| Setting | Default | Meaning |
|---|---|---|
code_root (--config) / LAZYTOOLS_CODE_ROOT |
server cwd | Directory every repo_path is confined to (and paths to repo_path in turn) — a caller cannot walk the reviewer out of it through an argument. The free-text task can still ask; the reviewer prompt refuses, but that is an instruction, not a sandbox, so keep secrets out of the root. |
LAZYTOOLS_CODE_REVIEW_MODEL |
the local ~/.codex/config.toml model |
Model override. |
LAZYTOOLS_CODE_REVIEW_EFFORT |
the CLI's default | Accepted vocabulary: none, minimal, low, medium, high, xhigh, max, ultra; actual support depends on model/runtime. |
LAZYTOOLS_CODE_REVIEW_TIMEOUT |
3600 |
Seconds per review. |
A review takes minutes, so give the host a matching tool timeout (Claude
Code: MCP_TOOL_TIMEOUT in ms) — otherwise the host cancels the call before
Codex answers.
claude_review — the same thing on the other model family¶
claude_code_review(task, repo_path=None, diff_ref=None, paths=None, session_id=None, session_name=None, model=None, effort=None) -> str
claude_ask(question, repo_path=None, session_id=None, session_name=None, model=None, thinking=None, effort=None) -> str
claude_ask mirrors codex_ask's consulting extras too: per-call model /
thinking / effort overrides (effort: low, medium, high, xhigh,
max), session_name, the same read-only LazyTools toolset (served to the
engine as its in-process MCP server), and the engine's own WebSearch/WebFetch
(web=True). claude_code_review gets that same web access — build it with
claude_reviewer(web=False) for the old offline behavior — but not the
LazyTools toolset.
Identical arguments and the identical durable-handle protocol (session_id=
instead of thread_id=), on ClaudeCodeEngine — so the same diff can go to
both and the answers can be compared. That is the point of having two: a
reviewer that shares none of your assumptions is worth more than a second
opinion from the same family.
Two differences come from the runtime, not from choice:
- no shell — the engine grants
Read/Glob/Grepscoped to the reviewed repository and nothing else, sogit_diff/git_statusare supplied as ordinary LazyBridge tools instead; - no native harness — the Agent SDK has no
review/start, so there is noclaude_review_changescounterpart.
Model via LAZYTOOLS_CLAUDE_REVIEW_MODEL (default sonnet), reasoning effort
via LAZYTOOLS_CLAUDE_REVIEW_EFFORT, extended thinking
via LAZYTOOLS_CLAUDE_REVIEW_THINKING; the confinement root and per-call
timeout are the same LAZYTOOLS_CODE_ROOT / LAZYTOOLS_CODE_REVIEW_TIMEOUT as
above. Registered as its own provider so a missing codex CLI cannot take the
Claude tools down with it, and vice versa.
code_write — let Codex / Claude Code edit¶
codex_write(task, cwd=None, thread_id=None, session_name=None, model=None, effort=None, approval_id=None) -> dict | str
claude_code_write(task, cwd=None, session_id=None, session_name=None, model=None, effort=None, approval_id=None) -> dict | str
Opt-in (--allow-unsafe), confined to the code root, and now run on the
LazyBridge engines like the review tools, with the same per-call model,
effort and session_name. codex_write no longer takes resume_last —
continue a conversation by session_name or the previous reply's thread_id.
In ungoverned legacy mode, Claude's writer edits inside its cwd and runs Bash behind an
allow-list gate; Bash is not path-confined, so treat the code root as fully
trusted scope.
code_sessions — see and manage session names¶
code_sessions_list(kind=None, repo_path=None, limit=50, since_days=None) -> dict
code_sessions_bind(kind, name, native_id, repo_path=None) -> dict
code_sessions_rename(kind, old, new, repo_path=None) -> dict
code_sessions_forget(kind, name, repo_path=None) -> dict
session_name aliases live in LazyBridge's SessionRegistry (a JSON file,
~/.lazybridge/sessions.json or LAZYBRIDGE_SESSIONS_FILE), keyed by
kind (codex or claude), the resolved repository and the name.
code_sessions_list is read-only and returns sessions, total (matching rows
before the limit) and returned (included count). Each session has name, kind,
native_id, scope, model, effort and updated_at. Sessions are sorted by
updated_at descending. The default limit is 50, capped at 200 (minimum 1).
Optional non-negative since_days keeps sessions updated within that many days;
all filters apply before counting and limiting. The three mutators adopt a thread you
already have (bind), rename, or drop a name (forget never deletes the
underlying conversation); they are only served with --allow-unsafe, and
repo_path is confined to the code root like every other path.
code_bridge — local and cloud coding jobs for other agents¶
code_bridge_submit(task, cwd=None, engine=None, where=None, tier=None, model=None, branch=None,
pr=None, open_pr=False, land=False, rebase_ok=False, review_of=None, allow_cloud=False) -> dict
code_bridge_status(job_id) -> dict
code_bridge_result(job_id) -> dict
The agent-facing twin of lazytools-code-bridge run | status | result (see
Code bridge): each tool runs that command and returns its JSON,
so one agent can hand work to Codex or Claude Code, local or in the cloud, and
read the outcome the way a person would. where="auto" (or [cloud]
default_where) places the job; land=true lands a finished cloud job (commit,
push, PR) without anyone running apply; review_of=<job> runs the opposite
engine and posts an independent-review comment on that job's PR. cwd is
confined to the code root, a task may not start with @, and a cloud job needs
allow_cloud=true on each call. Cloud results reach the repository only through the local landing step
(apply, land, or cloud-sync), which keeps its own checks. Only served
with --allow-unsafe.
dispatch — project dispatcher control¶
dispatch_status(project, last_n=50) reports task IDs and counts by status, active project jobs,
their pending tickets, the live dispatcher owner and recent JSON events. last_n is
bounded to 1,000. dispatch_wait(project, timeout_s=300, cursor="") waits for a new
approval ticket or actionable dispatcher outcome and returns events, a task-count
summary, and an advanced resumable cursor, including on timeout. The timeout is
bounded to 300 seconds. Reuse the cursor to avoid gaps and duplicates; transient store
read errors are retried within the wait. With --allow-unsafe, dispatch_start(project, repo_roots=None,
worktree_root=None, land=False, cwd=None) starts a detached supervised dispatcher and returns
the owner PID, launcher PID, and event log path after confirming ownership. If the child exits
first, the result reports failure and includes the new log tail. After 60 seconds a live
child without an owner returns status: "starting"; check dispatch_status.running
to confirm ownership. repo_roots maps repository slugs to checkout paths;
land opts into publication. cwd selects an existing checkout directory for tasks
that name no repository; when omitted, the dispatcher inherits the server's working
directory. A live project owner prevents another dispatcher.
The operator sets dispatch_launch_mode in the server configuration, and
dispatch_status reports it. legacy permits ungoverned launches exactly like
dispatch --launch-mode legacy.
dispatch_stop(project) requests a clean stop and waits up to 10 seconds; if it
returns running: true, the request remains pending. Running jobs continue and can
be adopted by the next dispatcher. Supervision logs unexpected exceptions and
retries after 5 seconds, doubling to a maximum of 5 minutes. It stops on a clean
exit or a shutdown request. Follow actionable dispatcher outcomes and approvals with
dispatch_wait; follow all job and approval changes with bridge_events
and decide tickets with bridge_approve or bridge_reject. These tools are never
available on task-scoped servers. Configure the same file-backed projects store for
the server and dispatcher with projects_store_db or LAZYTOOLS_PROJECTS_STORE_DB.
Configure the job, approval registry and lessons stores with the three config keys above
or their environment variables. The MCP server, dispatcher, doctor and child jobs inherit
these paths; use the same environment or CLI --db, --registry-db and --knowledge-db
options for CLI commands to share the same stores.
fleet — read-only code-bridge views¶
bridge_jobs(all=False) -> JSON
bridge_pending() -> JSON
bridge_route(tier, engine=None, where=None, needs=None) -> JSON
bridge_autonomy(week=None, since=None, until=None) -> JSON
bridge_models() -> JSON
capabilities_search(query="") -> rows
bridge_events(cursor="", timeout_s=0, projects=None) -> {"events": [...], "cursor": "..."}
bridge_approve(ticket, reason) -> dict # --allow-unsafe
bridge_reject(ticket, reason) -> dict # --allow-unsafe
bridge_cancel(job, reason) -> dict # --allow-unsafe
The fleet provider mirrors the corresponding lazytools-code-bridge CLI
commands in child processes. Its views are available in the default read-only
provider set without --allow-unsafe; the three deciding tools need it. The model view never opts into the quota-consuming
Claude probe. Routing choices and ISO dates are validated before invocation;
caller-provided values beginning with - are rejected rather than passed as
options. bridge_pending reports bridge job approval tickets and is separate
from the projects provider's pending approvals.
bridge_approve and bridge_reject run approve TICKET --ceo and
reject TICKET --ceo, and bridge_cancel runs cancel JOB. Each takes the
ticket id from bridge_pending (or a job id or unique prefix) and a non-empty
reason. They return ok, exit_code, the command's text in output, and its
error text in error. The caller decides as the CEO. The bridge does not record
who launched a job, so every job counts as one the CEO launched:
- An approval is allowed only when the owner's
autonomy policy delegates the ticket's class
to the CEO in the registry's current mode, and the owner has issued that
class's cards. Otherwise the call fails with "owner decision required" and the
ticket stays pending for the owner. A ticket without a class counts as
unknown, which is never delegated. - Rejection and cancellation are always allowed. Cancellation also rejects the job's open tickets.
- The ticket's reason records the decision as
actor=ceo mode=MODE class=CLASS: REASON. The job's manual interventions record the same text. A cancellation's reason starts withactor=ceo:.
No MCP tool changes the autonomy mode or the owner's cards. Those change only
through approver-credential autonomy with the owner credential. Like the views,
the deciding tools are never served to, or callable from, a scoped code task.
bridge_events is the orchestrator's single job and ticket event channel over
MCP. MCP calls are bounded, so it returns a cursor instead of streaming. Pass
the returned cursor to the next call:
-
projectsis a list of project names whose actionable dispatcher records are combined with job events. The configuredprojects_store_dbidentifies the dispatcher logs. The same project list must be supplied when resuming a cursor. -
An empty cursor means "from now", like the startup snapshot of
wait-any --all-active --loop --follow. Jobs that already finished and tickets that were already decided are not replayed. Tickets that are still open are reported. - An event that happens between two calls is returned by the next call that passes the previous cursor. This covers a job that starts and finishes, and a ticket that is created and decided, between the two calls.
- With
timeout_sgreater than 0 (at most 60), the call waits that long for at least one new event. Otherwise it returns at once, possibly with no events. - Event kinds are
approval,done,failed(alsopartialand failed cloud landing or review),interrupted,cancelled(an interrupted job that an operator cancelled or stopped), andlanded. Each event carrieskind,job_id,task_idanddetail(asdispatch --jsonevents do), plusstate,pr_urlandapproval.approval.statusgives the ticket's state when it was read (pending,approved,rejected,expired). - The cursor is opaque:
ev1.<compressed state>.<checksum>. The state lists the jobs already reported or finished before the cursor started (job id with its status or reported event) and the ticket ids already reported. A cursor that fails validation (wrong format, checksum or schema) is refused with an error. It is never silently reset. The cursor is checked for integrity but not signed with a secret. Its size grows with the number of finished jobs kept in the store, and ids of pruned jobs are dropped. - The tool only reads. Unlike
wait-any, it does not finish cloud jobs (refresh provider state, land, review). A cloud job'slandedevent, or itsfailedevent for a landing or review posting that failed, shows up once await,wait-any,cloud-syncorapply --landcaller has recorded the outcome, even ifdonewas already reported for that job. Each outcome is reported once; a retry that fails again is not a new event. - Event kinds come only from the stored job record (status and landing
metadata), so
wait-anyandbridge_eventsread the same record alike.
The event computation is shared with wait-any
(lazytools.code_bridge._events).
The CLI's wait-any --cursor [CURSOR] mode exposes the same resumable combined
payload. Omit the cursor value to attach "from now"; pass the returned value to
the next invocation so dispatcher records read in one batch are not lost between
one-shot waits.
Approval notifications¶
lazytools-orchestration-mcp --allow-unsafe also sends each new approval ticket
to the client as notifications/message, with level info. data is the
approval event exactly as bridge_events returns it, and
data.approval.approval_id is the ticket id.
- Each client session has its own loop. It starts when the client reports
initialized, readsbridge_eventsafter its own cursor every 2 seconds, and stops when the session closes. - As with an empty cursor, tickets already open when the session starts are sent
too. A session is sent each ticket once. The same ticket can also appear in
bridge_events, so de-duplicate by ticket id. - No loop runs without
--allow-unsafe, on a task-scoped server (code_task_context), whenfleetis not mounted, or onlazytools-mcp. - Delivery is best effort. Clients that do not receive log notifications,
including those speaking the 2026-07-28 protocol (which has no
initializedstep), keep pollingbridge_events, as must any client that cannot afford to miss a ticket. - The server declares the
loggingcapability for this. It acceptslogging/setLevelbut sends approval tickets whatever level is set.
knowledge — shared lessons¶
lessons_search(query, limit=5) -> list of lesson records
lessons_record(topic, what_worked, gotchas="") -> text # --allow-unsafe only
The store is the knowledge_db key of the --config file, else
LAZYTOOLS_KNOWLEDGE_DB, else ~/.lazytools/knowledge.sqlite. The dispatcher
uses --knowledge-db or LAZYTOOLS_KNOWLEDGE_DB; without either it does not use a
lessons store.
Topics follow the dispatcher's form, <repository>: <subject>. Recording an
existing topic revises that lesson; empty gotchas keeps the stored ones.
topic is limited to 200 characters and each text to 4000, and
credential-looking substrings are redacted. A new topic is also subject to
LazyBridge's 60-character slug limit; a refusal is returned as REJECTED: ....
Searching never creates the database.
pr — pull-request tools¶
pr_watch_poll(pulls, no_ci=False) -> {ok, events, terminal, errors}
pr_navigate(repo, pr, reviewer_cmd, checks, max_rounds=3) -> dict # --allow-unsafe
bridge_publish(task, repo, branch, base="main") -> dict # --allow-unsafe
bridge_apply(job, land=False) -> dict # --allow-unsafe
pr_watch_poll polls each owner/repo#number once with the code of
lazytools-code-bridge watch and returns only events not reported before. The
state lives in the bridge Store and is shared with a CLI watcher on the same
Store, so each event goes to whichever of the two polls first. It changes nothing
on GitHub and does not request reviews. A pull request that fails to poll is
listed under errors; the others are still returned.
The other three run navigate, publish and apply in a child process, so
approvals and landing checks are those of the CLI. pr_navigate waits for the
whole loop (max_rounds 1-10), and reviewer_cmd and checks are commands
executed on the server's machine. bridge_publish returns the command's text in
output, including the approval ticket. bridge_publish's repo and the job of
bridge_apply must be under the code root. None of the four tools is served to,
or callable from, a scoped code task.
Scoped code tasks¶
Set code_task_context in the server's trusted JSON configuration to serve the
configured task's code operations. Use a dedicated stdio process for its caller.
For HTTP, set http_token_env to the name of the environment variable holding the
task's bearer token. The server checks the token on every list and call.
{
"code_root": "/work/repo",
"code_task_context": {
"task_id": "project/review",
"actor": "worker",
"expires_at": "2027-01-01T12:00:00Z",
"folder": "/work/repo",
"profile": "read",
"tool_classes": ["read"],
"operations": ["codex_ask", "code_sessions_list"]
}
}
Mount the corresponding providers with --allow-unsafe. The live task, provider
inventory and native release report determine what is available. Configure the
same LAZYTOOLS_CODE_BRIDGE_CODEX_RELEASE_REPORT and
LAZYTOOLS_CODE_BRIDGE_CLAUDE_RELEASE_REPORT as for governed bridge runs.
Local governed turns use network-off policy and omit shell and application
tools. LazyBridge 1.9.0 has no governed launch evidence for
codex_review_changes, so use codex_code_review for scoped review.
The host can assign provider credentials using codex_api_key_env with
codex_credential_id or claude_api_key_env with claude_credential_id.
Credential IDs are executor-assigned UUIDs.
For a governed write, the first request returns an approval ID. The operator
can find it with lazytools-code-bridge pending and decide it with
lazytools-code-bridge approve ID or reject ID. Use the same projects DB for
both processes, via LAZYTOOLS_PROJECTS_STORE_DB or the server's
projects_store_db configuration. Retry the original invocation with its
approval_id. Approval authorizes one matching call within the task lease.
A scoped bridge submission requires the matching projects task ID and claim
token. Use a local read claim for review or an edit claim for writes.
Safety model¶
Structured tool results use strict JSON: non-finite floats (NaN, positive or
negative infinity, including NumPy floats) and pandas NA become null recursively.
This also applies to model/dataclass conversions and JSON serializer output.
Plain string and byte results retain their text behavior.
The server is read-only by default, enforced in two layers:
- Provider-level configuration (authoritative).
default_providers()constructs every provider in its read-only shape —DataHubTools()withoutallow_raw_series/allow_refresh,RegimeTools()withallow_write=False, which never even emit their write tools. - A name-based guard (secondary).
read_only=Trueadditionally drops any tool whose name matchesUNSAFE_TOOL_PATTERNS(e.g.*_send,*_write,*_delete,*_ensure_*,*_fit) with a logged warning — a coarse net for the case where a write-enabled provider is passed in by mistake.
There is no interactive ConfirmationGate over MCP, so mutating tools stay
off the default surface. To expose them you must opt in explicitly:
- CLI —
--allow-unsafeconstructs the providers in write-enabled mode (default_providers(ids, allow_write=True)) and disables the name guard, so the menu's writers (datahub refresh/register, regime fit/persist/delete) are emitted and served. No gating is applied. - Programmatic — build write-enabled providers yourself and pass
read_only=Falsetobuild_server, ideally with your own allow-list / confirmation wrapper around the mutating tools.
Programmatic use¶
import asyncio
from lazytools.mcp_server import build_server, serve_stdio, default_providers
# Read-only by default.
server = build_server(default_providers())
asyncio.run(serve_stdio(server))
build_server accepts any mix of ToolProviders, Tools, and plain
callables — so you can serve a custom, curated surface:
from lazytools.mcp_server import build_server
from lazytools.connectors.datahub import DataHubTools
from lazytools.statistical_analysis import StatisticalAnalysisTools
server = build_server(
[DataHubTools(), StatisticalAnalysisTools()],
name="lazytools-finance",
instructions="Read-only market data + statistics.",
)
API¶
lazytools.mcp_server ¶
LazyTools MCP server — expose LazyTools' tool providers over MCP.
The mirror of :mod:lazytools.connectors.mcp (the MCP client). Where the
client turns an external MCP server into lazybridge.Tool entries, this
server turns LazyTools' own providers into an MCP endpoint any host
(Claude Desktop, Claude Code, Codex, …) can call.
Quick start (stdio, the transport MCP hosts launch)::
python -m lazytools.mcp_server # all read-only providers
python -m lazytools.mcp_server datahub statistical # a subset
Claude Desktop / Claude Code config::
{
"mcpServers": {
"lazytools": { "command": "lazytools-mcp" }
}
}
Programmatic use::
import asyncio
from lazytools.mcp_server import build_server, serve_stdio, default_providers
server = build_server(default_providers()) # read-only by default
asyncio.run(serve_stdio(server))
Install with::
pip install "lazytoolkit[mcp] @ git+https://github.com/selvaz/LazyTools.git"
The server is read-only by default; see :func:build_server for the
safety model.
UNSAFE_TOOL_PATTERNS
module-attribute
¶
UNSAFE_TOOL_PATTERNS: tuple[str, ...] = ('_send', '_write', '_delete', '_register', '_ensure_', '_refresh', '_persist', '_save', 'save_', '_export_', '_fit', '_init_db', 'optimizer_run', 'optimizer_backtest', 'optimizer_create', 'tree_estimate', 'tree_backtest', '_create_draft', '-specialist', 'codex_', 'claude_code_review', 'claude_ask', 'code_bridge_', 'pr_navigate', 'pr_update', 'bridge_publish', 'bridge_apply', 'bridge_approve', 'bridge_reject', 'bridge_cancel', 'bridge_cloud_sync', 'bridge_resync', 'dispatch_start', 'dispatch_stop', 'code_sessions_bind', 'code_sessions_rename', 'code_sessions_forget', 'projects_close_task', 'projects_complete_todo', 'projects_edit_task', 'projects_mark_landed', 'tasks_claim', 'tasks_complete', 'tasks_route_clear', 'approvals_decide', 'lessons_record')
build_server ¶
build_server(providers: Sequence[Any], *, name: str = 'lazytools', version: str | None = None, read_only: bool = True, unsafe_patterns: Iterable[str] = UNSAFE_TOOL_PATTERNS, instructions: str | None = None, code_task_resolver: CodeTaskResolver | None = None, notify_approvals: bool = False) -> Server
Build a low-level MCP :class:~mcp.server.lowlevel.Server for providers.
The returned server has two handlers wired:
list_tools→ one MCPToolper expanded LazyBridge tool, withinputSchemataken verbatim fromtool.definition().parameters;call_tool→await tool.run(**arguments), the return value serialized via :func:result_to_text. Tool errors are returned as MCP error results (isError=True) instead of crashing the session.
With notify_approvals, each client session is also sent new approval
tickets as notifications, when the server serves bridge_events, is not
read-only and is not task-scoped.
Requires the mcp extra (pip install "lazytoolkit[mcp] @ git+https://github.com/selvaz/LazyTools.git").
Source code in src/lazytools/mcp_server/server.py
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
serve_stdio
async
¶
Run server over stdio until the client disconnects.
This is the transport Claude Desktop / Claude Code launch: the host spawns the process and speaks JSON-RPC over its stdin/stdout.
Source code in src/lazytools/mcp_server/server.py
default_providers ¶
default_providers(ids: list[str] | None = None, *, allow_write: bool = False, data_source: dict[str, Any] | None = None) -> list[Any]
Instantiate the default providers.
ids selects a subset (validated against :data:PROVIDER_FACTORIES);
None builds them all. allow_write is threaded to every factory —
False (default) yields read-only providers, True yields the
write-enabled shapes (the CLI's --allow-unsafe path). data_source
is ALSO threaded to every factory (each already accepts it -- path
for market-data-hub, regime_db_path for the regime depot, etc.) --
until this was wired up here, every factory's data_source parameter
was silent dead code: nothing ever called default_providers with one,
so it was always None no matter what a factory's own docstring
implied was configurable. See __main__.py's --config flag for
where a caller actually populates this now.
A factory that raises at construction time (rare — most only fail later,
at as_tools()) is skipped so one missing dependency never sinks the
server. A factory may return a single provider, or a list/tuple
of several (e.g. report's [ReportTools(...), ReportFiles(...)] —
the same shape lazytools.skills uses to wire the same two providers
for an agent) — either shape is flattened into the returned list.
Source code in src/lazytools/mcp_server/providers.py
expand_tools ¶
expand_tools(providers: Sequence[Any], *, read_only: bool = True, unsafe_patterns: Iterable[str] = UNSAFE_TOOL_PATTERNS) -> dict[str, Tool]
Expand providers into a name -> Tool map, isolating failures.
Each item may be a :class:lazybridge.Tool, a plain callable, an Agent,
or a ToolProvider (anything with as_tools()). Providers are
expanded independently: if one raises on expansion — typically an
ImportError because its optional extra is not installed (e.g.
RegimeTools without lazystats[regimes]) — it is skipped with a
warning and the rest still load. This is what lets a bare
pip install "lazytoolkit[mcp] @ git+https://github.com/selvaz/LazyTools.git" serve datahub + statistical while
regimes/web light up only once their extras are present.
On a name collision the last registration wins (with a warning),
mirroring build_tool_map(collision_policy="replace").
Source code in src/lazytools/mcp_server/server.py
result_to_text ¶
Serialize a tool's return value to a single text payload for MCP.
Plain strings pass through untouched; a string that is a JSON object or array (many providers return pre-serialized JSON) is re-emitted as strict JSON; bytes are decoded as UTF-8; everything else is rendered as strict JSON. Non-finite floats and pandas NA become null, including inside model/dataclass conversions and JSON serializers. Serialization errors propagate to the MCP error handler.