Comprehensive Curriculum • 42 Lessons • 32 Examples

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.

LESSON 01 Core

Quickstart and Streaming

Initialize client, configure session, stream response with system message, and track token usage.

examples/01_quickstart.mjs
LESSON 02 Core

Multi-Turn Chat and Parameters

ParameterBuilder, thoughtSignature propagation, message identity with MERCI_ID_KEY, and manual turn loop.

examples/02_conversation.mjs
LESSON 03 Core

Structured Data Extraction

Four approaches compared: response_format JSON schema, parallel tools, summary tools, and forced tool output.

examples/03_structured_output.mjs
LESSON 04 Core

Function Calling and Thinking

Auto/parallel/manual loops, forced tool control, thinking budget reasoning, and staged review reminders.

examples/05_tool_calling.mjs
LESSON 05 Core

Multimodal Vision and Media

Process image and document inputs across providers via createUnifiedMediaMessages with cross-wire normalization.

examples/10_multimodal.mjs
LESSON 06 Core

Embeddings and Model Tiers

The embedding surface, batch semantics, and the three environment-resolved model tiers that keep vendor ids out of your code.

examples/09_memory_and_todos.mjs
LESSON 07 Core

Observability and Error Handling

Client event subscriptions, typed error hierarchy (MerciError, BackendError), custom API observers, and AbortSignal.

examples/21_observability.mjs
LESSON 28 Core

Universal Event Telemetry

Full event surface inspection across all families with runId / parentRunId hierarchical correlation.

examples/21_observability.mjs
LESSON 08 Agentic

Agent Loops and Skills

AgentLauncher REPL, skills library discovery, slash commands, Human-in-the-Loop gates, and checkpoint persistence.

examples/07_agent_loop.mjs
LESSON 09 Agentic

Shell Tool Security Gate

Three-layer security gate (safe, blocked, and HITL approval) for shell execution with synthesis fallback.

examples/14_coding_agent.mjs
LESSON 10 Agentic

Model Context Protocol (MCP)

McpClient integration: spawn local/remote MCP servers, discover schema tools, and flatten content for Gemini.

examples/24_mcp_client.mjs
LESSON 11 Agentic

Agent-to-Agent (A2A) Protocol

Agent cards discovery, HTTP JSON-RPC delegation, and cross-agent event telemetry tracing.

examples/26_a2a.mjs
LESSON 12 Agentic

Persistent Memory and Distillation

LocalFile and Composite memory providers, asynchronous background distillation, eager preload, and recency fallback.

examples/09_memory_and_todos.mjs
LESSON 17 Agentic

Todos and Compaction

Task state management with withTodos, progress tracking, and custom history compaction with loss markers.

examples/09_memory_and_todos.mjs
LESSON 13 Advanced

DAG Workflows and Replan

WorkflowPlanner, WorkflowExecutor, and WorkflowEvaluator: automated plan generation, step execution, and replanning.

examples/17_dag_workflow.mjs
LESSON 14 Advanced

Hierarchical Sub-DAG Workflows

Nested Y/X-axis planners with a first-class nested DAG (engine: dag), objective inheritance, and depth-capped sub-DAGs.

examples/17_dag_workflow.mjs
LESSON 15 Advanced

Multi-Agent Discussion and Consensus

DiscussionSession: structured debate rounds, passing criteria, LLM judge evaluation, and synthesis aggregation.

examples/19_discussion.mjs
LESSON 16 Advanced

Distributed Multi-Agent Swarms

Unify local and remote A2A HTTP agents into one cohesive discussion swarm with mesh coordination.

examples/26_a2a.mjs
LESSON 18 Advanced

DAG Workflows with Shared Task State

Synchronize task state across independent DAG steps using a shared TodoStore for discovery and remediation.

examples/17_dag_workflow.mjs
LESSON 19 Advanced

State Machine Orchestration

LLM-planned state machines, mid-run transition mutation, checkpoint/resume, and deterministic graph evaluation.

examples/18_state_machine.mjs
LESSON 20 Advanced

Subagent Orchestration and Briefs

Agentic orchestration using the task tool, specialized profiles, structured briefs, withObjective, and artifacts.

examples/15_delegation.mjs
LESSON 21 Advanced

Plan-and-Execute Architecture

Split planning and execution stages with withPlan/withExecute, human approval checkpoints, and store handoffs.

examples/16_plan_and_execute.mjs
LESSON 22 Advanced

Verified State Machines

Verification gates on nodes, completion fingerprints, RetryLedger loop prevention, and LLM-as-a-judge validation.

examples/18_state_machine.mjs
LESSON 23 Advanced

Multi-Engine DAG Stage Planning

Dynamic per-step engine execution: embed nested StateMachines and Discussion sessions inside DAG steps.

examples/17_dag_workflow.mjs
LESSON 24 Advanced

MAA Vertical Planning

Multi-Agent Architecture: runTasks with subagent_type and verification, planForEach sub-pipelines, and conclude verdict.

examples/19_discussion.mjs
LESSON 25 Advanced

Subagents Across 4 Engines

Benchmark delegation across Naive, DAG, StateMachine, and MAA engines with background detached subagents.

examples/15_delegation.mjs
LESSON 26 Advanced

Context Management and Compaction

Objective threading, foldContext deterministic markers, compaction loss markers, SM context window, and save_artifact.

examples/15_delegation.mjs
LESSON 27 Advanced

Resilience, Retry Policies and Security

Retry error classification, abort-aware exponential backoff, sliding-window stream timeouts, and credential redaction.

examples/08_resilience.mjs
LESSON 29 Advanced

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.

examples/23_evals.mjs
LESSON 30 Core

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

examples/04_judgment.mjs
LESSON 31 Core

Approvals and safety: the refund agent that must be stopped

guardrails, permission rules, approval modes, per-tool timeout, money budget

examples/06_approvals_and_safety.mjs
LESSON 32 Agentic

Web tools: search, scrape, and the headless browser

web search, scrape, and the headless browser

examples/11_web_tools.mjs
LESSON 33 Agentic

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

examples/12_knowledge_graph.mjs
LESSON 34 Agentic

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

examples/13_knowledge_corpus.mjs
LESSON 35 Agentic

A crash mid-run, resumed exactly once

session checkpoints, the at-most-once execution journal, the session fork

examples/20_durability.mjs
LESSON 36 Agentic

Telemetry: the same run, as an OTLP envelope on disk

the OTLP envelope, the gen_ai span tree, redaction, batching

examples/22_telemetry.mjs
LESSON 37 Advanced

Your SDK is the MCP server

your SDK as an MCP server over Streamable HTTP, capabilities, artifacts, loadable components

examples/25_mcp_server_http.mjs
LESSON 38 Advanced

merci behind an editor protocol

the ACP v1 agent: session lifecycle, updates, the fail-closed permission model

examples/27_acp_agent.mjs
LESSON 39 Advanced

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

examples/29_workflow_contract.mjs
LESSON 40 Advanced

An unattended queue that retries, parks and resumes

work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines

examples/30_scheduler.mjs
LESSON 41 Advanced

One call: policy + scheduler + workspace + operator

one <code class="inline">createOrchestration</code> call binding policy, scheduler, workspace and operator; the spend ledger

examples/31_orchestration.mjs
LESSON 42 Advanced

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

examples/32_agent_files.mjs
32 runnable examples

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.

01 .mjs
01_quickstart.mjs

initialize a client, discover models, stream one turn, read usage

02 .mjs
02_conversation.mjs

one carried history, request parameters, the vendor knobs, prompt caching, a stdin-safe REPL

03 .mjs
03_structured_output.mjs

JSON Schema and Zod output with bounded corrections

04 .mjs
04_judgment.mjs

discriminative models: noul/choice/score, the typed read, role clients, one decision gate

05 .mjs
05_tool_calling.mjs

autonomous, parallel and manual tool calls, output schemas, the object cap

06 .mjs
06_approvals_and_safety.mjs

guardrails, permission rules, approval modes, per-tool timeout, money budget

07 .mjs
07_agent_loop.mjs

the agentic loop, staged follow-ups, streamed input, in-flight steering, a leased durable inbox (drainInbox), abort, budgets, limits

08 .mjs
08_resilience.mjs

retries, fan-out limits, the circuit breaker, stream timeouts

09 .mjs
09_memory_and_todos.mjs

a persistent memory bank with embeddings, lazy vs preloaded recall, durable todos

10 .mjs
10_multimodal.mjs

vision and document ingestion into structured output

11 .mjs
11_web_tools.mjs

web search, scrape, and the headless browser

12 .mjs
12_knowledge_graph.mjs

the typed graph: mechanical pass, model enrichment, edge shapes, the decision gate, read-only curated BM25 retrieval

13 .mjs
13_knowledge_corpus.mjs

one corpus → surfaces → wiki projection → adopted ontology → a versioned custom-builder cache that survives an edit

14 .mjs
14_coding_agent.mjs

a workspace-scoped coding agent: context tools, the shell gate, YAML skills

15 .mjs
15_delegation.mjs

the task tool, the spawn roster and registry, one context-transfer policy for every hand-off

16 .mjs
16_plan_and_execute.mjs

plan → approve → execute with a durable handoff

17 .mjs
17_dag_workflow.mjs

DAG plan → execute → evaluate, a replan, a nested child DAG

18 .mjs
18_state_machine.mjs

a node graph with a completion contract

19 .mjs
19_discussion.mjs

a decision group: task DAG → debate → judge → conclude

20 .mjs
20_durability.mjs

session checkpoints, the at-most-once execution journal, the session fork

21 .mjs
21_observability.mjs

correlation (runId/parentRunId), hooks, phases, custom observers, typed errors, abort

22 .mjs
22_telemetry.mjs

the OTLP envelope, the gen_ai span tree, redaction, batching

23 .mjs
23_evals.mjs

a scored suite, a recorded cassette, an LLM judge, the failure taxonomy

24 .mjs
24_mcp_client.mjs + 24_mcp_server.mjs

an MCP stdio server's tools, sampling/elicitation/roots, resources and prompts

25 .mjs
25_mcp_server_http.mjs

your SDK as an MCP server over Streamable HTTP, capabilities, artifacts, loadable components

26 .mjs
26_a2a.mjs + 26_a2a_server.mjs

discover an A2A peer, delegate to it, drive its task lifecycle

27 .mjs
27_acp_agent.mjs

the ACP v1 agent: session lifecycle, updates, the fail-closed permission model

28 .mjs
28_workspace_isolation.mjs

one directory or git worktree per item, hooks, path confinement, withWorkspace, a todo store as a work source

29 .mjs
29_workflow_contract.mjs

a repo-owned WORKFLOW.md: strict parsing, the template subset, last-known-good reload

30 .mjs
30_scheduler.mjs

work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines

31 .mjs
31_orchestration.mjs

one createOrchestration call binding policy, scheduler, workspace and operator; the spend ledger

32 .mjs
32_agent_files.mjs

*.agent.yaml definitions: load, freeze, resolve the toolset, run live, delegate live