Test with emulators
Run integrations and conformance cases offline against service emulators.
Experimental.
@yolk-sdk/conformanceand@yolk-sdk/emulatorsmay change in any canary release. Both are new after0.1.0-canary.95; keep every@yolk-sdk/*package on the same version, and use emulators in tests and local development only.
Use emulators when your host app's tests should exercise the real connector, provider, or MCP client code without calling the outside service. This guide covers the host side: wiring an emulator into your own tests, running the conformance cases against it, and the rules you must respect. The Emulator APIs and Conformance APIs pages hold the full per-service detail.
Cases, emulators, and evidence
- A conformance case is a small Effect program that states one claim about how a provider
behaves on the wire (
docsversuswire), with asafetyofread,write-reversible, orwrite-irreversible. The same case runs against replayed fixtures, an emulator, or a live practice account; only the layers change. - A fixture is a committed recording of the exchanges a case relies on. Fixtures hold synthetic or scrubbed data only.
- An emulator is a stand-in that answers from those committed fixtures. The Dropbox, Notion, Todoist, Telegram, GitHub, Google, LinkedIn search, MCP, email, R2, OpenCode Go, and subscription-usage emulators are fixture-only: they never invent an answer. Fortnox and Microsoft Graph add a few documented extrapolations, and the model-route emulators (Gateway, OpenAI, Anthropic, Codex, Grok) generate synthetic output or scripted turns in the recorded wire shapes. Each emulator passes its service's conformance cases offline, so the cases prove that the emulator matches the claims your code relies on.
- Evidence says how far to trust a claim. An emulated route is
unverifiedwhen it follows synthetic placeholders andverifiedwhen it follows a live recording, dated by the route'sobservedAt; fixtures make the same distinction with their own dates. Responses from an unverified HTTP route carryx-emulator-evidence: unverified; the email and R2 port fakes record the evidence on each ledger entry instead. Unverified connector write routes are pending: the Yolk repository holds them in a time-bounded allowlist until an owner-approved live run verifies them. See Evidence for the current state of each route.
A passing test against an emulator shows that your code agrees with the recorded claims. It does not show that the live provider still behaves that way.
Test an integration in-process
This runnable example runs the real GitHub connector against the in-process GitHub emulator in a Vitest test. It lists labels, absorbs a rate limit, and shows a refused request.
Install (Node 22 or later):
pnpm add @yolk-sdk/connectors@canary @yolk-sdk/agent@canary effect@4.2.0
pnpm add -D @yolk-sdk/emulators@canary @yolk-sdk/conformance@canary vitesttest/github-emulator.test.ts:
import { Effect, Layer } from 'effect'
import { afterEach, beforeEach, expect, it } from 'vitest'
import {
BearerTokenCredential,
makeCredentialBinding,
makeIntegration,
type ConnectorHttpClient,
type CredentialResolver
} from '@yolk-sdk/connectors'
import {
connectorHttpClientsFromEffectHttpClientLayer,
staticCredentialResolverLayer
} from '@yolk-sdk/connectors/conformance'
import {
githubConnectorId,
githubCreateIssueAction,
githubListLabelsAction,
githubTokenSlotId
} from '@yolk-sdk/connectors/github'
import {
githubEmulatorOrigin,
makeGithubEmulator,
type GithubEmulator
} from '@yolk-sdk/emulators/github'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'
// The practice repository the emulator's default seed holds.
const integration = makeIntegration({
connectorId: githubConnectorId,
config: { owner: 'yolk-synthetic', repo: 'conformance-practice' },
credentialBindings: [
makeCredentialBinding({ slotId: githubTokenSlotId, credentialRef: 'test-github-token' })
]
})
let github: GithubEmulator
beforeEach(async () => {
github = await makeGithubEmulator()
})
afterEach(async () => {
await github.close()
})
// Run the real connector over an HttpClient that calls the emulator in-process.
const run = <A, E>(effect: Effect.Effect<A, E, ConnectorHttpClient | CredentialResolver>) =>
Effect.runPromise(
effect.pipe(
Effect.provide(
Layer.mergeAll(
connectorHttpClientsFromEffectHttpClientLayer.pipe(
Layer.provide(
InProcessHttpClient.layer([EmulatorRoute.handler(githubEmulatorOrigin, github.fetch)])
)
),
staticCredentialResolverLayer(
BearerTokenCredential.make({ token: 'synthetic-github-test-token' })
)
)
)
)
)
const listLabels = githubListLabelsAction.executeTyped({ integration, input: { perPage: 2 } })
it('lists labels from the seeded repository', async () => {
expect(await run(listLabels)).toMatchObject({ _tag: 'Success', value: { hasNextPage: true } })
expect(
github.ledger.entries().map(entry => `${entry.method} ${entry.route} ${entry.status}`)
).toEqual(['GET /repos/{owner}/{repo}/labels 200'])
})
it('surfaces a 429 with retry-after, then answers the retry', async () => {
github.faults.add({ kind: 'status', status: 429, headers: { 'retry-after': '7' }, count: 1 })
expect(await run(listLabels)).toMatchObject({
_tag: 'Failure',
error: { code: 'github_rate_limited', status: 429, retryAfterMs: 7000 }
})
expect(await run(listLabels)).toMatchObject({ _tag: 'Success' })
expect(github.ledger.entries().map(entry => [entry.status, entry.fault])).toEqual([
[429, 'status'],
[200, undefined]
])
})
it('refuses an unrecorded request and writes nothing; reset restores the seed', async () => {
const seed = github.snapshot()
const createIssue = (extra: { readonly labels?: ReadonlyArray<string> }) =>
githubCreateIssueAction.executeTyped({
integration,
input: { title: 'yolk-test issue', body: 'Synthetic.', ...extra }
})
// No fixture records a create with labels: one ledgered 400 not-emulated.
expect(await run(createIssue({ labels: ['bug'] }))).toMatchObject({
_tag: 'Failure',
error: { status: 400 }
})
// Assert that it was refused, not the exact reason text, which may be reworded.
expect(github.ledger.entries()[0]?.notEmulated).toEqual(expect.any(String))
expect(github.snapshot()).toEqual(seed)
// The recorded create flow is emulated; reset() puts the seed back.
expect(await run(createIssue({}))).toMatchObject({ _tag: 'Success', value: { number: 42 } })
await github.reset()
expect(github.snapshot()).toEqual(seed)
expect(github.ledger.entries()).toEqual([])
})Run:
pnpm exec vitest run test/github-emulator.test.tsExpected result: 3 passed. No request leaves the process, and the token is never stored or
written to the ledger.
InProcessHttpClient.layer calls the emulator's fetch handler directly. Your code keeps calling
the real origin (https://api.github.com), and a request to an origin without a route fails with
an HttpClientError that names only the origin.
Serve an emulator on loopback
Use @yolk-sdk/emulators/node when the code under test must go through a real socket, for
example to check streaming or your own FetchHttpClient stack. EmulatedHttpClient rewrites the
routed origin to the loopback server. The server binds only to 127.0.0.1.
Fragment (inside an async test):
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { githubEmulatorOrigin, makeGithubEmulator } from '@yolk-sdk/emulators/github'
import { startFetchHandlerServer } from '@yolk-sdk/emulators/node'
import { EmulatedHttpClient, EmulatorRoute } from '@yolk-sdk/emulators/router'
const github = await makeGithubEmulator()
const server = await startFetchHandlerServer(github.fetchOn(githubEmulatorOrigin))
const httpLayer = EmulatedHttpClient.layer([
EmulatorRoute.url(githubEmulatorOrigin, server.url)
]).pipe(Layer.provide(FetchHttpClient.layer))
// ... run the code under test with httpLayer, then:
await server.close()
await github.close()The rewrite loses the origin. The Dropbox, Notion, GitHub, Google, LinkedIn search, and MCP
emulators answer each route only on its recorded origin, so serve their fetchOn(origin) rather
than fetch, with one server per origin for the services that have two (Dropbox, Google, LinkedIn
search, and MCP with its afloat profile). The Fortnox, Microsoft Graph, Todoist, Telegram, model-route, and OpenCode Go emulators
have no fetchOn: serve their fetch. Microsoft Graph serves both of its origins from one server.
Each emulator's reference section names its origins. In Effect tests,
serveFetchHandler is the scoped variant.
Seeds and profiles
The connector, MCP, email, and R2 emulators start from a typed seed. The default seed holds the
fixtures' synthetic entities, so the fixture seeds of the conformance cases (for example
githubConformanceFixtureSeeds) match it. Most connector emulators take a profile (default or
empty; Fortnox has its own profiles), and the other seed keys replace parts of it; LinkedIn
search and MCP take no profile. The emulators that mint timestamps (Fortnox, Microsoft Graph,
Dropbox, Notion, Todoist, Telegram, GitHub, Google) take an injectable now clock that keeps them
deterministic. Each emulator's reference section lists its seed keys.
Fragment:
const github = await makeGithubEmulator({
seed: { profile: 'empty' },
now: () => Date.parse('2026-01-01T12:00:00Z')
})
await github.seed({ profile: 'default' }) // replace the state; reset() now restores this
await github.reset()An invalid seed fails with the emulator's input-invalid error, such as
GithubEmulatorInputInvalid. On the connector and MCP emulators, snapshot() returns a deep copy
of the state.
Faults and retries
On the HTTP connector emulators (Fortnox through LinkedIn search in the
table) and MCP, faults.add adds a status fault: matching requests answer
an error status instead of the route's answer, so nothing is written. match narrows it by
method and path (a trailing * makes a prefix) and, except on Fortnox and Microsoft Graph, by
route (a manifest route template); count limits how many requests it answers. MCP also takes
truncate-after-chunks, and the model-route and OpenCode Go emulators take their own status and
chunk faults, matched by path and model.
The email and R2 port fakes take { kind: 'failure', method, match?, count?, failure } instead
(R2 also names the port): a call to that method whose request contains match as a deep subset
answers failure, and no state changes. See Email and
R2.
A 429 fault with retry-after reaches the GitHub connector as github_rate_limited with
retryAfterMs; each emulator's reference section names the code its connector or provider maps it
to. Connector actions return that failure and do not retry by themselves, so retry policy stays
host-owned. A fault with count: 1 proves that your retry succeeds on the next attempt, as in the
second test above.
On every HTTP connector emulator and MCP, a fault is chosen only for a request the emulator would
answer, so a refused request never uses one up and a misplaced fault stays listed in
faults.list() instead of passing silently. On Fortnox and Microsoft Graph, a refusal is the
provider's error envelope (a 404 for an unknown id, or a 400 or 409 for a state or value the route
refuses) rather than the shared { error: { type: 'not_emulated' } } 400, and it uses up no fault
either.
Drills
Drill knobs are test-only. The Microsoft Graph, Dropbox, Notion, Todoist, Telegram, GitHub, Google,
LinkedIn search, and MCP emulators take a drills option, and Fortnox takes quirks. Each knob
makes the emulator disagree with one conformance claim, so the matching case fails. Most knobs are
booleans; Microsoft's timestampPrecisionDigits is a number. Use drills to prove that a case can
fail against your setup, not to model provider behaviour. See the conformance example below for a
drill run.
Read the ledger and the control plane
On the fixture-only stateful emulators (Dropbox, Notion, Todoist, Telegram, GitHub, Google,
LinkedIn search, and MCP), ledger.entries() records every request in arrival order: method,
path, route template, query and body with credential-named keys redacted, status, evidence, any
fault, and, for a refusal, the notEmulated reason. All of them except Todoist and Telegram also
record the non-credential headers they check. Other ledgers differ:
- Fortnox ledgers queries and bodies as sent, without redaction.
- Microsoft Graph redacts credential-named keys and records the
Preferheader. - Neither Fortnox nor Microsoft Graph has a
notEmulatedfield: their refusals appear as provider-envelope statuses (such as 401, 404, or 400). - The model-route, email, and R2 ledgers have their own shapes.
Each emulator's reference section describes its ledger. coverage() lists each manifest route
with its request count and case ids.
The HTTP emulators also serve a control plane under /_emulate/* from the same fetch handler. On
the connector and MCP emulators it serves ledger (GET, DELETE), faults (GET, POST,
DELETE), reset (POST), state (GET), seed (POST), and coverage (GET). The
model-route emulators serve script instead of seed, and the emulators built from several parts
(OpenCode Go, and the usage part of Anthropic, Codex, and xAI) serve each part under
/_emulate/<part>/*. Use the control plane when the test process does not hold the emulator
object, for example when another process runs the code under test.
Fragment (with server from the loopback fragment):
const control = (path: string, init?: RequestInit) =>
fetch(`${server.url}/_emulate/${path}`, init).then(response => response.json())
await control('faults', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ kind: 'status', status: 503, match: { method: 'POST' }, count: 1 })
})
const { entries } = await control('ledger')
await control('reset', { method: 'POST' })Reset between tests
On the connector and MCP emulators, reset() restores the current seed and clears the ledger,
faults, and runtime data such as cursors and sessions. Create one emulator per test, as in the
example, or call reset() in beforeEach. Run write flows sequentially on one emulator: some
emulators, such as Todoist, accept only the one
created item a fixture records at a time, and refuse a second one until the first is gone or the
emulator is reset.
Unexpected requests fail loudly
Emulators fail closed. On the fixture-only emulators, a request that no fixture records is
answered with one ledgered 400 not-emulated ({ error: { type: 'not_emulated', message } })
before anything is written and before any fault is chosen. That includes other routes, other query
parameters or body keys, unknown ids, cursors the emulator did not issue, and, on the emulators
that check the origin (Dropbox, Notion, GitHub, Google, LinkedIn search, MCP), another origin.
GitHub, Google, LinkedIn search, MCP, Todoist, and Telegram ledger a request on no emulated route
shape with constant text only (/<unrecognised>). Fortnox and Microsoft Graph refuse in the
provider's error envelope (404 for an unknown route, 400 for an unsupported query or body), and
the model-route emulators answer an unknown route with a 404. Each emulator's reference section
lists exactly what it accepts.
A connector may map that 400 to an ordinary validation code (github_validation for GitHub), so
assert the ledger as well as the result:
// Fragment: fails the test when the code under test sent anything no fixture records.
expect(github.ledger.entries().filter(entry => entry.notEmulated !== undefined)).toEqual([])The email and R2 emulators are port-level fakes: they answer { notEmulated: { reason } }
instead of an HTTP 400.
Run the conformance cases against an emulator
Run a service's cases with runConformance, giving each case fresh connector ports over a fresh
emulator. The runner builds layer(testCase) once per case in its own scope, so a scoped layer
that creates the emulator, as below, opens and closes one per case. An emulator created outside
the layer factory, or captured in one shared Layer.succeed value, is not rebuilt: its state is
shared across cases.
Fragment (a Vitest test, with the imports of the runnable example plus these):
import {
GithubConformanceConfig,
githubConformanceCases,
githubConformanceFixtureSeeds
} from '@yolk-sdk/connectors/github/conformance'
import {
conformanceReportFailed,
formatConformanceReport,
runConformance
} from '@yolk-sdk/conformance/runner'
import { type GithubEmulatorOptions } from '@yolk-sdk/emulators/github'
const githubCasePorts = (options: GithubEmulatorOptions = {}) =>
Layer.unwrap(
Effect.acquireRelease(
Effect.promise(() => makeGithubEmulator(options)),
github => Effect.promise(() => github.close())
).pipe(
Effect.map(github =>
Layer.mergeAll(
connectorHttpClientsFromEffectHttpClientLayer.pipe(
Layer.provide(
InProcessHttpClient.layer([EmulatorRoute.handler(githubEmulatorOrigin, github.fetch)])
)
),
staticCredentialResolverLayer(
BearerTokenCredential.make({ token: 'synthetic-github-test-token' })
),
Layer.succeed(GithubConformanceConfig, githubConformanceFixtureSeeds)
)
)
)
)
it('passes every GitHub case against the emulator', async () => {
const report = await Effect.runPromise(
runConformance(githubConformanceCases, {
target: { kind: 'in-process' },
layer: () => githubCasePorts()
})
)
expect(conformanceReportFailed(report), formatConformanceReport(report)).toBe(false)
})
it('fails exactly the drilled case', async () => {
const report = await Effect.runPromise(
runConformance(githubConformanceCases, {
target: { kind: 'in-process' },
layer: () => githubCasePorts({ drills: { contentUnfolded: true } })
})
)
expect(report.results.filter(result => result.status === 'failed').map(r => r.id)).toEqual([
'github.contents.base64-file'
])
})Every case runs on in-process and emulated targets, write cases included, because nothing real
happens there. A case that no live run has observed carries an unverified-case warning, as the
GitHub cases do. Use { kind: 'emulated' } with the loopback layer for the socket path.
A failure against an emulator means that the SDK code, the case, and the emulator's copy of the
fixtures no longer agree. Common causes are an SDK upgrade whose requests changed shape (look for
notEmulated in the ledger), a seed that does not match the case's config, or an intended drill.
It says nothing new about the live provider. A failure against a live practice account is the
signal that the provider changed.
What emulators do not do
- No invented answers. The fixture-only emulators refuse anything a fixture does not record, including empty pages or empty search results where no fixture records one, and listings no fixture shows. They never guess a status or an error envelope.
- Limited leftover lookups. The read-only GitHub, Google, and Todoist
find*ConformanceLeftoverslookups send only reads a read case records, so they run against the emulator and report a leftover the state holds. The Google draft search and free-text event query are recorded only empty, so they fail not-emulated once the state holds a draft or an event that might match (the event cases leave their cancelled run events). The Dropbox and Notion lookups fail against the default seed (no fixture records an empty listing or search), but report a leftover in a recorded shape that a seed or an earlier case left behind. The repository runners report a failed lookup as a lookup-failedWARN, not as leftovers. - No delivery. Sends such as the Telegram message or the Gmail practice send are recorded in the emulator's state and never delivered anywhere.
- No production use. The Fortnox through MCP subpaths and the loopback server are Node only,
and the router layers refuse to build when
NODE_ENVisproduction.
Credentials
- Use synthetic credentials only, never a real token. Emulators are test stand-ins, not secret-scrubbing boundaries.
- Use a credential each emulator recognises. GitHub, Google, LinkedIn search, and MCP accept only
a synthetic bearer in the
b64tokenform their sections define (see GitHub).synthetic-github-test-tokenqualifies; a UUID or an all-hex key does not. Such a bearer also suits the other bearer emulators. Telegram takes a synthetic<digits>:<secret>bot token instead. The MCPafloatprofile (https://useafloat.com) takesafloat_followed by such a bearer, for exampleafloat_synthetic-key-0001. - Send the credential only where the provider expects it, such as the
Authorizationbearer or Telegram's bot token in the path. There it is never stored or ledgered. - Checks for a credential repeated elsewhere in a request differ by emulator:
- GitHub, Google, and LinkedIn search refuse a repeat in the path, query, recorded headers, or body.
- MCP also checks every other header.
- Todoist and Telegram check the path, query, and body.
- Dropbox, Notion, Fortnox, Microsoft Graph, and the model routes do not check repeats, so a credential sent elsewhere can reach the ledger (Fortnox ledgers queries and bodies unredacted).
- MCP's guarantee has precise limits: some emulator constants and control-plane data are not checked. See MCP.
- The
/_emulate/*control plane is the host's own trusted surface. Seed and fault data you give it is stored and returned as given, so never put a secret in a seed, fault body, or header.
Live runs
Emulators and replay cover everyday tests. Run the cases live only by hand, against practice accounts you own, with the account owner's approval; never in CI.
- In your host, run the same cases with your own
HttpClientandtarget: { kind: 'live', account }. Live targets always runreadcases. They run awrite-reversiblecase only withallowWrites: 'reversible', and awrite-irreversiblecase only when its exact id is inallowIrreversible. The two gates are independent:allowWritesnever starts an irreversible case, and leaving it out does not stop one listed inallowIrreversible. See the runner safety policy. - In the Yolk repository, the
pnpm conformance:<id>runners (for examplepnpm conformance:github) dry-run by default: they print the plan without a network call or a credential read.--live --owner-approved --account <label>is refused wheneverCIis set. Recordings from a live run are promoted by hand and scrubbed, so committed fixtures stay synthetic.
Each service's runner flags, seeds, and cleanup rules are on its page under Connectors and in Conformance APIs.
Available emulators
Import an explicit subpath; there is no root export.
| Subpath | Stands in for | Used with | Reference |
|---|---|---|---|
@yolk-sdk/emulators/router | Routing only | Any Effect HttpClient code | Router |
@yolk-sdk/emulators/node | Loopback server | EmulatedHttpClient | Node server |
@yolk-sdk/emulators/gateway | Vercel AI Gateway chat completions and classifier | @yolk-sdk/agent/providers/vercel/ai-gateway-provider, ai-gateway-classifier | Gateway |
@yolk-sdk/emulators/openai | OpenAI Chat Completions | @yolk-sdk/agent/providers/openai/provider | OpenAI |
@yolk-sdk/emulators/anthropic | Anthropic Messages and Claude usage | @yolk-sdk/agent/providers/anthropic/claude-provider | Anthropic |
@yolk-sdk/emulators/codex | ChatGPT Codex Responses and usage | @yolk-sdk/agent/providers/openai/codex-provider | Responses |
@yolk-sdk/emulators/xai | xAI Grok CLI proxy Responses and billing | @yolk-sdk/agent/providers/xai/grok-provider | Responses |
@yolk-sdk/emulators/opencode | OpenCode Go chat, Messages, Responses, and usage | @yolk-sdk/agent/providers/opencode/go-provider | OpenCode Go |
@yolk-sdk/emulators/email | EmailClient port (fake backend) | @yolk-sdk/connectors/email | |
@yolk-sdk/emulators/r2 | R2Presigner and R2ObjectClient ports | @yolk-sdk/connectors/r2-storage | R2 |
@yolk-sdk/emulators/fortnox | Fortnox /3 API | @yolk-sdk/connectors/fortnox | Fortnox |
@yolk-sdk/emulators/microsoft | Microsoft Graph (Outlook, OneDrive, calendar) | @yolk-sdk/connectors/microsoft | Microsoft |
@yolk-sdk/emulators/dropbox | Dropbox /2 RPC and upload | @yolk-sdk/connectors/dropbox | Dropbox |
@yolk-sdk/emulators/notion | Notion /v1 | @yolk-sdk/connectors/notion | Notion |
@yolk-sdk/emulators/todoist | Todoist API v1 | @yolk-sdk/connectors/todoist | Todoist |
@yolk-sdk/emulators/telegram | Telegram Bot API | @yolk-sdk/connectors/telegram | Telegram |
@yolk-sdk/emulators/github | GitHub REST | @yolk-sdk/connectors/github | GitHub |
@yolk-sdk/emulators/google | Gmail, Calendar, and Drive | @yolk-sdk/connectors/google | |
@yolk-sdk/emulators/linkedin-search | Exa and Enrich Layer | @yolk-sdk/connectors/linkedin-search | LinkedIn search |
@yolk-sdk/emulators/mcp | Two synthetic MCP servers, Afloat and Figma endpoints | @yolk-sdk/mcp/client, @yolk-sdk/connectors/{afloat,figma}/conformance | MCP |
@yolk-sdk/emulators/kie | Kie Market API task read and create | @yolk-sdk/connectors/kie | Kie |