Merci SDK Tutorials
A complete, progressive tour from foundational streaming to distributed multi-agent swarms. Each tutorial explains the core architecture, wire behavior, and runnable patterns.
Try refining your search query or filter selection.
Quickstart and Streaming
Initialize client, configure session, stream response with system message, and track token usage.
Multi-Turn Chat and Parameters
ParameterBuilder, thoughtSignature propagation, message identity with MERCI_ID_KEY, and manual turn loop.
Structured Data Extraction
Four approaches compared: response_format JSON schema, parallel tools, summary tools, and forced tool output.
Function Calling and Thinking
Auto/parallel/manual loops, forced tool control, thinking budget reasoning, and staged review reminders.
Multimodal Vision and Media
Process image and document inputs across providers via createUnifiedMediaMessages with cross-wire normalization.
Embeddings and Model Tiers
The embedding surface, batch semantics, and the three environment-resolved model tiers that keep vendor ids out of your code.
Observability and Error Handling
Client event subscriptions, typed error hierarchy (MerciError, BackendError), custom API observers, and AbortSignal.
Universal Event Telemetry
Full event surface inspection across all families with runId / parentRunId hierarchical correlation.
Agent Loops and Skills
AgentLauncher REPL, skills library discovery, slash commands, Human-in-the-Loop gates, and checkpoint persistence.
Shell Tool Security Gate
Three-layer security gate (safe, blocked, and HITL approval) for shell execution with synthesis fallback.
Model Context Protocol (MCP)
McpClient integration: spawn local/remote MCP servers, discover schema tools, and flatten content for Gemini.
Agent-to-Agent (A2A) Protocol
Agent cards discovery, HTTP JSON-RPC delegation, and cross-agent event telemetry tracing.
Persistent Memory and Distillation
LocalFile and Composite memory providers, asynchronous background distillation, eager preload, and recency fallback.
Todos and Compaction
Task state management with withTodos, progress tracking, and custom history compaction with loss markers.
DAG Workflows and Replan
WorkflowPlanner, WorkflowExecutor, and WorkflowEvaluator: automated plan generation, step execution, and replanning.
Hierarchical Sub-DAG Workflows
Nested Y/X-axis planners with a first-class nested DAG (engine: dag), objective inheritance, and depth-capped sub-DAGs.
Multi-Agent Discussion and Consensus
DiscussionSession: structured debate rounds, passing criteria, LLM judge evaluation, and synthesis aggregation.
Distributed Multi-Agent Swarms
Unify local and remote A2A HTTP agents into one cohesive discussion swarm with mesh coordination.
DAG Workflows with Shared Task State
Synchronize task state across independent DAG steps using a shared TodoStore for discovery and remediation.
State Machine Orchestration
LLM-planned state machines, mid-run transition mutation, checkpoint/resume, and deterministic graph evaluation.
Subagent Orchestration and Briefs
Agentic orchestration using the task tool, specialized profiles, structured briefs, withObjective, and artifacts.
Plan-and-Execute Architecture
Split planning and execution stages with withPlan/withExecute, human approval checkpoints, and store handoffs.
Verified State Machines
Verification gates on nodes, completion fingerprints, RetryLedger loop prevention, and LLM-as-a-judge validation.
Multi-Engine DAG Stage Planning
Dynamic per-step engine execution: embed nested StateMachines and Discussion sessions inside DAG steps.
MAA Vertical Planning
Multi-Agent Architecture: runTasks with subagent_type and verification, planForEach sub-pipelines, and conclude verdict.
Subagents Across 4 Engines
Benchmark delegation across Naive, DAG, StateMachine, and MAA engines with background detached subagents.
Context Management and Compaction
Objective threading, foldContext deterministic markers, compaction loss markers, SM context window, and save_artifact.
Resilience, Retry Policies and Security
Retry error classification, abort-aware exponential backoff, sliding-window stream timeouts, and credential redaction.
Evals and the Cassette
Score a suite of runs with runEvals and the built-in scorers, record the vendor calls once, and replay the suite offline with the same verdicts.
Judgment: typed answers, then a gate in code
discriminative models: <code class="inline">noul</code>/<code class="inline">choice</code>/<code class="inline">score</code>, the typed read, role clients, one decision gate
Approvals and safety: the refund agent that must be stopped
guardrails, permission rules, approval modes, per-tool timeout, money budget
Web tools: search, scrape, and the headless browser
web search, scrape, and the headless browser
The knowledge graph: a contract that can say no
the typed graph: mechanical pass, model enrichment, edge shapes, the decision gate, read-only curated BM25 retrieval
A corpus that becomes a wiki, and survives an edit
one corpus → surfaces → wiki projection → adopted ontology → a versioned custom-builder cache that survives an edit
A crash mid-run, resumed exactly once
session checkpoints, the at-most-once execution journal, the session fork
Telemetry: the same run, as an OTLP envelope on disk
the OTLP envelope, the gen_ai span tree, redaction, batching
Your SDK is the MCP server
your SDK as an MCP server over Streamable HTTP, capabilities, artifacts, loadable components
merci behind an editor protocol
the ACP v1 agent: session lifecycle, updates, the fail-closed permission model
The workflow contract: one repo-owned file, from config to prompt
a repo-owned <code class="inline">WORKFLOW.md</code>: strict parsing, the template subset, last-known-good reload
An unattended queue that retries, parks and resumes
work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines
One call: policy + scheduler + workspace + operator
one <code class="inline">createOrchestration</code> call binding policy, scheduler, workspace and operator; the spend ledger
Agent definition files: one YAML, a live tool-using agent, a live subagent
<code class="inline">*.agent.yaml</code> definitions: load, freeze, resolve the toolset, run live, delegate live
Every example in the repository
The 42 lessons above tell the story; these are the files you run. Each links to its source, and
pnpm run test:examples audits them offline.
initialize a client, discover models, stream one turn, read usage
one carried history, request parameters, the vendor knobs, prompt caching, a stdin-safe REPL
JSON Schema and Zod output with bounded corrections
discriminative models: noul/choice/score, the typed read, role clients, one decision gate
autonomous, parallel and manual tool calls, output schemas, the object cap
guardrails, permission rules, approval modes, per-tool timeout, money budget
the agentic loop, staged follow-ups, streamed input, in-flight steering, a leased durable inbox (drainInbox), abort, budgets, limits
retries, fan-out limits, the circuit breaker, stream timeouts
a persistent memory bank with embeddings, lazy vs preloaded recall, durable todos
vision and document ingestion into structured output
web search, scrape, and the headless browser
the typed graph: mechanical pass, model enrichment, edge shapes, the decision gate, read-only curated BM25 retrieval
one corpus → surfaces → wiki projection → adopted ontology → a versioned custom-builder cache that survives an edit
a workspace-scoped coding agent: context tools, the shell gate, YAML skills
the task tool, the spawn roster and registry, one context-transfer policy for every hand-off
plan → approve → execute with a durable handoff
DAG plan → execute → evaluate, a replan, a nested child DAG
a node graph with a completion contract
a decision group: task DAG → debate → judge → conclude
session checkpoints, the at-most-once execution journal, the session fork
correlation (runId/parentRunId), hooks, phases, custom observers, typed errors, abort
the OTLP envelope, the gen_ai span tree, redaction, batching
a scored suite, a recorded cassette, an LLM judge, the failure taxonomy
an MCP stdio server's tools, sampling/elicitation/roots, resources and prompts
your SDK as an MCP server over Streamable HTTP, capabilities, artifacts, loadable components
discover an A2A peer, delegate to it, drive its task lifecycle
the ACP v1 agent: session lifecycle, updates, the fail-closed permission model
one directory or git worktree per item, hooks, path confinement, withWorkspace, a todo store as a work source
a repo-owned WORKFLOW.md: strict parsing, the template subset, last-known-good reload
work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines
one createOrchestration call binding policy, scheduler, workspace and operator; the spend ledger
*.agent.yaml definitions: load, freeze, resolve the toolset, run live, delegate live