Explore, call and build MeshCall services (typed streaming RPC between Python, TypeScript and Go through the MeshCall Router). Use when a project depends on the meshcall package or meshcall-go module, when asked to call or inspect a mesh service, or when writing or changing an @service / ServiceMeta / meshcall.NewService.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Is that skill safe to install?
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
Are you the author of Meshcall?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/anywhere-labs-meshcall)
---
name: meshcall
description: Explore, call and build MeshCall services (typed streaming RPC between Python, TypeScript and Go through the MeshCall Router). Use when a project depends on the meshcall package or meshcall-go module, when asked to call or inspect a mesh service, or when writing or changing an @service / ServiceMeta / meshcall.NewService.
---
# MeshCall
Typed streaming RPC over WebSocket and HTTP across Python, TypeScript and Go.
## Core Architecture (4 Layers)
1. **Layer 1 — Service & Contract (`@service`, `@query`, `@mutates`, `@stream`)**:
A **service** groups versioned methods under a canonical name (`chat.v1.Chat`). Each method's parameters, return model, docstring/description and annotations (`read_only`, `idempotent`, `destructive`, `deprecated`) form its **contract**, which the runtime validates on every call and reports to the Router.
- **Four method shapes**:
- `unary`: single request → single response (`@query` for pure read-only/idempotent calls, `@mutates` for state-changing calls).
- `server_stream`: single request → stream of output items (`@stream` returning `AsyncIterator[Out]`).
- `client_stream`: initial parameters + stream of input items → single response (`@mutates` with `AsyncIterator[In]` as its last parameter).
- `duplex`: initial parameters + concurrent bidirectional item stream (`@mutates(reason="…")` with `DuplexChannel[In, Out]` as its last parameter, returning `None`).
- **Targeted services** (`@service("…", targeted=True)`): services whose instances hold distinct in-memory state (a session, a loaded model, an actor). Instead of load-balancing across instances, callers address a specific instance: a generated client is bound to one when it is constructed, a raw call passes `instance="<instance_id>"`.
2. **Layer 2 — Router (`Router` / `LocalRouter`)**:
Peers never connect directly to each other's ports; all services and clients connect to a stateless **Router** (`ws://127.0.0.1:8765` by default) that maintains the live service registry, validates deadlines, deduplicates idempotent calls and load-balances across healthy instances.
- `Router(url=None)` is a pure endpoint descriptor pointing to an external Router (`ws://`, `wss://`, `http://`, `https://`, `unix://`, `pipe://`, or a list of failover URLs; defaults to `MESHCALL_ROUTER_URL` or `"ws://127.0.0.1:8765"`). When cluster edge Routers advertise `--cluster-public-url`, Go, Python, TypeScript, Swift, and JVM WebSocket runtimes automatically discover healthy sibling edges via `meshcall.router.v1.Endpoints/list` and fail over across them on reconnect (never downgrading `wss://` to `ws://`).
- `LocalRouter(port=0, ...)` manages a local `meshcall-router` OS subprocess. Start it explicitly with `async with LocalRouter(port=0) as router:` (Python) / `await using router = await LocalRouter.start(...)` (TypeScript) / `meshcall.StartLocalRouter(ctx, ...)` (Go), or pass an unstarted `LocalRouter(port=8765)` directly to `Mesh(...)` to let `Mesh` start and stop the subprocess automatically.
3. **Layer 3 — Mesh (`Mesh(router)`)**:
The peer runtime in your process. A `Mesh` connects to a `Router` or `LocalRouter`, mounts local services (`mesh.mount(svc)` then `mesh.run()` or `async with mesh.serve():` in Python, `await mesh.serve()` or `await using _ = await mesh.startServing()` in TypeScript, `mesh.Serve(ctx)` in Go), multiplexes outgoing client calls over one shared connection, and exposes the Router's built-in services on `mesh.registry` (`list() -> list[RegistryService]` where each item has `.name`, `.version`, `.description`, `.targeted`, `.instances`, `.methods`; `describe(service)`) and `mesh.auth` (`whoami`, `issue_token`, `renew_token`, `revoke_token`, `list_tokens`). A temporary token's expiry refuses new connections only (live ones stay up until `revoke_token`); `renew_token(token_id, ttl_seconds=…)` extends it without a new secret (`invalid_argument` / `token_expired` once expired or revoked: issue a new one); a holder whose credential is replaced elsewhere passes a function instead of the value (`token=` / `tunnel=` in Python and TypeScript, `WithTokenSource` / `WithTunnelSource` in Go), which the runtime asks before every connection and again when the Router refuses the old credential; `ttl_seconds` may reach the Router's `--token-max-ttl` (30 days by default). `issue_token` also accepts an optional `principal` (up to 512 UTF-8 bytes) that the Router injects as `meshcall-token-principal` on every routed call (exposed on Router connections as `ctx.token_principal` / `ctx.tokenPrincipal` / `ctx.TokenPrincipal`, stripped if forged by a caller, and scoped into unary idempotency deduplication).
4. **Layer 4 — Generated Client (`<Service>Client(mesh)`)**:
Generated by `meshcall generate`. Takes a `Mesh`, exposes typed methods with the **exact same business parameter list and order** as the server handler, and configures per-call transport options (`timeout`, `idle_timeout`, `metadata`, `idempotency_key`, `instance`) via `.with_options(...)` / `.withOptions(...)` / `.WithOptions(...)`.
## Explore before you code
```bash
meshcall router inspect # services, instances, health, methods
meshcall router inspect chat.v1.Chat --json # one service with its full contract
```
Each method line shows shape (`unary` / `server_stream` / `client_stream` /
`duplex`), parameters, annotations (`read_only`, `idempotent`,
`destructive`, `deprecated`), the description
and, for duplex, its reason. `--router ws://host:port` or
`MESHCALL_ROUTER_URL` selects the Router (default `ws://127.0.0.1:8765`;
`unix:///path` for a Unix socket, `pipe://NAME` for a Windows named pipe);
`--auth user:pass` / `--token T` when accounts are configured;
`--tunnel mtun_…` connects through a tunnel (one instance's scoped methods
only, no `--instance` needed; the CLI does not seal calls, so an end-to-end
tunnel answers `tunnel_e2e_required`). `inspect` also lists the tunnels and
temporary tokens you issued (expiry, live connections), never their secrets;
`meshcall token renew TOKEN_ID --ttl 720h` renews a token.
## Call
```bash
meshcall call chat.v1.Chat.send '{"session_id":"s1","text":"hi"}'
meshcall call demo.v1.Counter.count '{"n":5}' # server stream: one JSON line per item
printf '{"value":1}\n{"value":2}\n' | meshcall call demo.v1.Sum.sum '{"offset":10}' --stdin
meshcall call chat.v1.Chat.talk '{"session_id":"s1"}' --stdin # duplex: each stdin line is sent as read
```
Flags: `--json` (machine-readable output and errors), `--timeout 10s`,
`--metadata k=v`, `--idempotency-key K`, `--idle-timeout D`, `--instance ID`
(address one instance; required for services `inspect` marks `[targeted]`,
and the error hint lists the live instance ids). The request is one JSON
object whose keys are the method's parameters. Do not write throwaway
scripts to probe a service; use these two commands.
Over plain HTTP (same port, no client needed): `curl
http://HOST:8765/v1/call/svc.v1.Name/method -d '{json}'`. Server streams
come back as NDJSON envelopes: `{"item": …}` per item, then `{"end":
{"trailers": …}}` or `{"error": …}` (read `.item` with `jq`); client streams
take an NDJSON body (first line the request); duplex is WebSocket-only.
Headers: `Authorization`, `MeshCall-Timeout-Ms` (unary calls default to 30
s), `Idempotency-Key`, `MeshCall-Instance`, `MeshCall-Meta-<key>`. Errors are
the same JSON envelope with an HTTP status (400, 401, 403, 404, 429, 503,
504…). `GET /v1/openapi.json` describes every method you may call (feed it to
Swagger UI or a client generator); `GET /v1/services` is the Registry.
`meshcall call … --http` does the same from the CLI. In a browser or edge
runtime, pass `new Mesh(new Router("wss://…"), { token })` (or `{ tunnel }`)
from `meshcall/web` to the generated TypeScript client: `wss://` is a
WebSocket with every shape including duplex plus `mesh.mount(...)` /
`mesh.startServing()` (credentials go in `hello`),
`https://` the HTTP API without duplex or serving; add `--http-cors-origin` for pages on
other origins.
## Read errors
Every error has `code`, `message`, `details.source` (`client` | `router` |
`server`) and often `details.reason`.
| code | meaning | what to do |
| --- | --- | --- |
| `invalid_argument` | your request failed validation; `details.violations` lists `{path, code, message}` per field. `reason: instance_required` means the service is targeted; `idempotency_key_on_duplex` that duplex calls take no key; `reserved_metadata` that a metadata key starts with `meshcall-` (any case) | fix the named fields; pass `--instance` / `instance=` for targeted services; drop the key; rename the metadata key |
| `method_not_found` | wrong service or method | the hint lists available methods |
| `unavailable` | no instance (`no_instances`), instance lost, every breaker open (`circuit_open`), the named instance is unknown / draining, a tunnel or lost cluster node's instance is reconnecting (`instance_offline`), an in-flight cluster forward lost its node (`node_lost`), another cluster node still holds the `instance_id` (`4503` `instance_id_held`), the cluster store is unreachable (`4503` `cluster_store_unavailable`), or the Router is stopping (`router_draining`, `router_shutdown`) | `router inspect`; retry if `retryable` (or retry registration on `4503`) |
| `resource_exhausted` | Router, connection or every instance at capacity (`overloaded`); a tunnel at its `max_connections` (HTTP 429 / close 4429); a request, response or stream item over the frame limit (`frame_too_large`, not retryable) | back off and retry; split oversized data into stream items |
| `protocol_error` | a stream item beyond the consumer's credit (`flow_control_violation`) or another frame that broke the protocol | fix the producer; regenerate a hand-patched client |
| `deadline_exceeded` | `timeout_ms` elapsed (source says who noticed) | raise the timeout or make the handler faster |
| `permission_denied` | the caller (possibly the anonymous user: no credentials sent) may not make this call; the same error whether or not the method exists. `reason: tunnel_scope`: on a tunnel connection, outside the tunnel (`details.instance_id` is its instance); `tunnel_rejected`: the instance refused `tunnels.open` (or does not hold the pinned `e2e_key`); `tunnel_e2e_required`: a plain or HTTP call on an end-to-end tunnel; `e2e_peer_required`: the instance serves this service only to clients that authenticated with a key of their own (configure an `E2EIdentity`); `policy_violation`: the Router closed the connection (1008) and the message says why, e.g. an `instance_id` outside the credential's `instance_ids` | send credentials, or add `service/method` to the account, key or token; on a tunnel pass its instance or ask the issuer for wider scopes |
| `unauthenticated` | the credentials are wrong, expired or revoked (HTTP 401 at connect, or close 4401); `reason: tunnel_revoked` / `tunnel_closed` / `key_changed`: the tunnel ended (later calls on the same Mesh keep that answer); `token_revoked`: the temporary token was revoked; an instance stops re-registering once refused, and `run` / `serve` ends with this error when every Router refused it; `e2e_handshake_failed`: the instance does not hold the key the client pinned, or refused the client's own key or pairing (never retried, never falls back to plaintext or to a weaker handshake); `e2e_session_unknown`: the instance lost its end-to-end session (the runtime handshakes again on the next call and retries a unary call once); `e2e_frame_rejected`: a sealed frame was altered on the way (only that call ends) | get a new credential (on a tunnel: ask the issuer again); retrying with the same one fails the same way; for `e2e_handshake_failed` check the pinned key with the issuer, or pair the client again |
| `internal` | the service failed; `reason: invalid_response` means its own handler broke its contract | read the service's log, fix the service |
Never guess at parameters when `invalid_argument` tells you the path.
## Write a service
**1:1 Server ↔ Client parameter lists.** Whatever business parameters a server
method declares (after stripping DI dependencies and `meta` parameters), the
generated client method in Python, TypeScript and Go takes that **exact same
parameter list and order** (0 parameters → `()`, N parameters → `(p1, p2, …)`,
client stream → `(p1, …, items)`). Service names carry a version and are
normalised (`chat` → `chat.v0`; `chat.v1`, `demo.v1.Greeting` are fine).
Docstrings/descriptions and annotations are part of the contract: tooling,
retries and LLM tool exposure depend on them.
Python (`@query`, `@stream`, `@mutates`, `DuplexChannel`, `@dependency`, `meta`, `Router`, `LocalRouter`, `Mesh`):
```python
from collections.abc import AsyncIterator
from typing import Annotated
from pydantic import BaseModel
from meshcall import DuplexChannel, Mesh, Router, dependency, meta, mutates, query, service, stream
class Message(BaseModel):
text: str
@dependency
async def current_user(authorization: Annotated[str, meta("authorization")] = "") -> str:
return authorization.removeprefix("Bearer ") or "anonymous"
@service("chat.v1.Chat")
class Chat:
"""Chat sessions."""
@query
async def greet(self, name: str) -> Message:
"""Pure read-only query (`read_only=True, idempotent=True`)."""
return Message(text=f"hello {name}")
@mutates(idempotent=True)
async def send(self, session_id: str, text: str, user: str = current_user) -> Message:
"""Append a message and return the reply (`user` is injected on the server only)."""
return Message(text=f"{user}: {text}")
@stream
async def history(self, session_id: str) -> AsyncIterator[Message]:
"""Server stream (`AsyncIterator[Out]` return type)."""
yield Message(text="…")
@mutates
async def ingest(self, session_id: str, items: AsyncIterator[Message]) -> Message:
"""Client stream (ordinary parameters first, `AsyncIterator[In]` parameter last)."""
async for item in items: ...
return Message(text="ok")
@mutates(reason="Interactive voice/chat turn")
async def talk(self, session_id: str, channel: DuplexChannel[Message, Message]) -> None:
"""Duplex stream (`DuplexChannel[In, Out]` parameter, returns `None`)."""
async for msg in channel:
await channel.send(Message(text=f"ack {msg.text}"))
if __name__ == "__main__":
mesh = Mesh(Router("ws://127.0.0.1:8765"))
mesh.mount(Chat())
mesh.run()
```
TypeScript (`@query`, `@stream`, `@mutates`, `dependency`, `meta`, `Router`, `LocalRouter`, `Mesh`):
```typescript
import { dependency, meta, Mesh, mutates, query, Router, service, stream, z, type DuplexChannel } from "meshcall";
const Message = z.object({ text: z.string() }).meta({ id: "Message" });
const currentUser = dependency(
(authorization: string) => authorization.replace(/^Bearer\s+/, ""),
{ inject: [meta("authorization", { default: "" })] },
);
@service("chat.v1.Chat", { description: "Chat sessions." })
export class Chat {
@query({
description: "Pure read-only greeting.",
input: { name: z.string() },
output: Message,
})
async greet(name: string) {
return { text: `hello ${name}` };
}
@mutates({
description: "Append a message from the caller.",
idempotent: true,
input: { session_id: z.string(), text: z.string() },
output: Message,
inject: [currentUser],
})
async send(session_id: string, text: string, user: string) {
return { text: `${user}: ${text}` };
}
@stream({
description: "Stream messages in a session.",
input: { session_id: z.string() },
output: Message,
})
async *history(session_id: string) {
yield { text: "…" };
}
}
const mesh = new Mesh(new Router("ws://127.0.0.1:8765"));
mesh.mount(new Chat());
await mesh.serve();
```
In TypeScript, `input: { ... }` declares positional business parameters (`(p1, p2, ...)`), client streams use `@mutates({ description, input, streamInput: ItemSchema, output: ReplySchema })` (handler receives `(..., items: AsyncIterable<Item>)`), and duplex methods use `@mutates({ description, reason, input, streamInput: InSchema, streamOutput: OutSchema })` (handler receives `(..., channel: DuplexChannel<In, Out>)`).
Go (`github.com/t4wefan/meshcall/meshcall-go`; struct-based `ServiceMeta` or `NewService` + `HandleUnary` / `HandleServerStream` / `HandleClientStream` / `HandleDuplex`, `Dependency`, `Meta[T]`, `NewRouter`, `StartLocalRouter`, `NewMesh`):
```go
type ChatService struct {
meshcall.ServiceMeta `service:"chat.v1.Chat" description:"Chat sessions."`
Send meshcall.MethodMeta `method:"send" shape:"unary" idempotent:"true" description:"Append a message and return the reply."`
}
func (s *ChatService) SendHandler(ctx *meshcall.Context, sessionID string, text string) (Message, error) {
return Message{Text: sessionID + ": " + text}, nil
}
mesh := meshcall.NewMesh(meshcall.NewRouter("ws://127.0.0.1:8765"))
if err := mesh.Mount(&ChatService{}); err != nil {
log.Fatal(err)
}
_ = mesh.Serve(ctx)
```
Rules the runtime enforces or warns about (set `MESHCALL_STRICT=1` while
you edit so warnings fail fast with a `hint` that says exactly what to add):
- Every service and method has a description (docstring in Python; `description`
field in TypeScript decorators and Go struct tags / `meshcall.Doc(...)`).
- A service whose instances hold distinct state (a session, a loaded model,
an actor) is `targeted=True` / `targeted: true`: callers must name the
instance: a generated client is bound to one when constructed
(`WorkerClient(mesh, instance="worker-3")`, `new WorkerClient(mesh, "worker-3")`,
`NewWorkerClient(mesh, "worker-3")`); handlers read `ctx.instance_id` /
`ctx.instanceId`.
- `@query` marks pure reads (`read_only=True, idempotent=True`); `@mutates(idempotent=...)`
or `@mutates(destructive=True)` marks state-changing methods. Retry policies
only retry idempotent calls.
- Raise `MeshCallError(code, message, retryable=…, details=…)` for
application errors; anything else becomes a sanitised `internal`.
- Dependencies (`@dependency` / `dependency()` / `Dependency()`) and `meta("key")`
are resolved before the handler runs and are never exposed in the public
contract or generated clients. Handlers may also declare `ctx: RpcContext`
and `logger: RpcLogger` parameters when needed.
## Generate and use a typed client
Generate a typed client instead of hand-writing frames:
```bash
uv run meshcall generate my_app.service:Chat --output generated/chat-client
uv run meshcall generate my_app.service:Chat --language typescript --output generated/chat-ts
meshcall generate service.meshcall.json --language go --output generated/chatgo
meshcall generate service.meshcall.json --language swift --output Sources/App/Generated
meshcall generate service.meshcall.json --language kotlin --package-name com.example.chat --output app/src/main/kotlin/chat
```
Swift clients (`meshcall-swift`, iOS and macOS, client side only) are one file
of `Codable` types plus an `async` client: `ChatClient(mesh).send(...)`, server
streams are `for try await` sequences, and `Mesh(tunnel: grant)` takes the
issuer's tunnel answer (`router_url`, `credential`, `instance_id`, `e2e_key`) as is.
Kotlin clients (`meshcall-jvm`, Android and the JVM, client side only) are one
file of kotlinx.serialization classes plus a client: suspend functions,
server streams as cold `Flow`s, and `…Async` methods (CompletableFuture,
StreamObserver) for Java; `Mesh(Router(url), MeshOptions(tunnel = credential, e2eKey = key))`.
Pass `--single-file --output chat_client.py` (Python) when you want a single module instead of an installable package directory. In TypeScript or Go projects without Python, pass a `.ts` service file (`npx meshcall generate src/service.ts:Chat ...`) or a contract JSON file (`meshcall.WriteContract` in Go).
Per-call options (`timeout`, `idle_timeout`, `metadata`, `idempotency_key`, `instance`)
are configured via `.with_options(...)` / `.withOptions(...)` / `.WithOptions(...)` so
business method signatures stay 100% identical to the server handler:
Python:
```python
async with Mesh(Router("ws://127.0.0.1:8765"), token="...") as mesh:
services = await mesh.registry.list() # each item has .name, .instances, .methods
chat = ChatClient(mesh)
reply = await chat.with_options(timeout=5.0, idempotency_key="k1").send("s1", "hello")
```
TypeScript:
```typescript
await using mesh = await Mesh.connect(new Router("ws://127.0.0.1:8765"), { token: "..." });
const services = await mesh.registry.list(); // each item has .name, .instances, .methods
const chat = new ChatClient(mesh);
const reply = await chat.withOptions({ timeoutMs: 5000, idempotencyKey: "k1" }).send("s1", "hello");
```
Go:
```go
mesh, err := meshcall.ConnectMesh(ctx, meshcall.NewRouter("ws://127.0.0.1:8765"), meshcall.WithToken("..."))
defer mesh.Close()
services, err := mesh.Registry().List(ctx) // each item has .Name, .Instances, .Methods
chat := chatclient.NewChatClient(mesh)
reply, err := chat.WithOptions(meshcall.CallOptions{Timeout: 5 * time.Second}).Send(ctx, "s1", "hello")
```
## Best practices
The shape of a good MeshCall project (`best-practice/` in the MeshCall repo
is a complete example):
```text
my_app/
├── src/my_app/service.py # @service classes and their Pydantic models; no transport code
├── src/my_app/server.py # Mesh(Router() | LocalRouter(...)).mount(...).run(), config from env
├── generated/<svc>-client/ # generated client package, checked in, regenerated on contract change
└── tests/test_service.py # LocalRouter(port=0) + Mesh(router), generated client against it
```
**Designing a service**
- One service per bounded capability (`chat.v1.Chat`, `billing.v1.Invoices`);
methods are verbs on it. Bump the version segment (`chat.v2.Chat`) for an
incompatible change and run both until clients move; never edit a shipped
method's parameters in place. Mark replaced methods
`deprecated="new_method"` so clients see it at compile time. *Adding* a
method is a rolling deploy: the Router routes each method over the
instances that have it, so new and old instances coexist.
- Keep the request flat: parameters are the request. Reach for a model-typed
parameter only for a reusable structure (`profile: Profile`); never wrap
everything in one `request` object.
- Return a model, never a bare scalar or dict: `-> Message`, not `-> str`.
Response models are the contract other languages generate from.
- Service instances hold process-local state and dependencies: construct
them yourself (`mesh.mount(Chat(store, llm))`) and guard shared
state with a lock; the server reuses one instance across concurrent calls.
- Annotate honestly. `read_only` implies `idempotent`; generated clients
mark idempotent calls so `RetryPolicy` retries them on retryable
`unavailable` / `resource_exhausted`. `destructive` methods are never
retried without an idempotency key, and tooling asks before invoking them.
A method that creates a record is *not* idempotent unless it dedupes on
`ctx.idempotency_key`.
- Errors: raise `MeshCallError("my_app.v1.quota_exceeded", "…", retryable=False,
details={"limit": 100})` for domain failures with a namespaced code;
use the standard codes (`invalid_argument` for semantic validation the
schema cannot express, `permission_denied`, `resource_exhausted`) when they
fit. Let unexpected exceptions propagate: they become a sanitised
`internal` and are logged with the traceback. Do not catch-and-wrap.
- Streams: a server stream per *long or incremental* result (LLM tokens,
export rows, live event feeds); a client stream when the caller produces data
over time (uploads, telemetry). Yield as you go, do not buffer the whole
result. Credit-based flow control is automatic, so a slow consumer slows the
producer rather than exhausting memory. Streams are never retried: make
the caller able to restart from a known point.
- Duplex (`@mutates(reason="…")`, handler takes `channel:
DuplexChannel[In, Out]`, returns `None`) only when output must interleave
with input that keeps arriving *in one call* (a voice or chat turn that
is answered while the user is still sending). It gives up retry,
deduplication, idempotency keys, `idempotent` / `read_only`, HTTP access
and rebalancing (one instance for the whole call). First try a server
stream plus unary calls (`subscribe` + `send`), or a client stream. If you
use it, read output concurrently with sending (a task per direction): a
side that only sends stalls once the other side's credit runs out.
- Respect cancellation and deadlines: check `ctx.remaining()` before an
expensive step; in Python an `asyncio.CancelledError` means the caller
left, clean up and re-raise. TypeScript handlers get `ctx.signal`.
- Log with the injected `logger` (it already carries service, method,
`call_id`); never `print`. For tracing, add the OpenTelemetry interceptors
on both sides (`meshcall.otel.client_interceptor()` /
`server_interceptor()` with `pip install "meshcall[otel]"`, `meshcall/otel`
in TypeScript): trace context
rides in call metadata across languages and the Router. Router metrics:
`--metrics-listen 127.0.0.1:9464`. Put request-scoped facts in trailers
(`ctx.set_trailer("cache", "hit")`) when callers should see them.
**Calling a service**
- Use the generated client, check it in, regenerate when the contract
changes (`uv run meshcall generate … --output generated/<svc>-client`); a
CI step that regenerates and diffs catches a drifted client at compile
time of the consumer.
- Always pass a `timeout=`; streams also get `idle_timeout=`. The service,
the Router and the client enforce it independently, so a stuck instance
cannot hold a call forever.
- Send an `idempotency_key=` (a UUID per logical operation) on every
mutating unary call you might retry; the Router dedupes concurrent and
recent duplicates, and `RetryPolicy` is then allowed to retry it.
- Propagate tracing/auth through `metadata=` using a client interceptor
(set once, applies to every call) rather than adding parameters.
- Catch typed errors: `except UnavailableError` / `instanceof
DeadlineExceededError`; check `error.retryable` before retrying anything
the built-in `RetryPolicy` did not cover.
**Running it**
- `mesh.run()` handles `SIGINT` / `SIGTERM` and drains in-flight calls automatically. When managing lifecycle manually (`async with mesh.serve():` in Python, `await using _ = await mesh.startServing()` or `await mesh.drain()` in TypeScript, `mesh.Drain(ctx)` in Go), draining removes the instance from the Router pool first so a rolling deploy fails nothing.
- Give every instance a stable, meaningful `instance_id` (`Mesh(router, instance_id="chat-host-1")`);
`router inspect`, error `details.instance_id` and `ctx.instance_id`
show it. Targeted calls skip balancing and the breaker, so a stuck node
stays reachable for diagnosis but also stays blamed by its callers.
- Set `max_inflight` on `Mesh(router, max_inflight=...)` for instances with a real capacity limit (GPU, DB pool)
so the Router routes around full instances instead of queueing on them.
- Point services and clients at **all** Routers (`Router([uri1, uri2])`); no
Router-side coordination is needed.
- Keep `MESHCALL_STRICT=1` in CI so missing descriptions and unannotated
mutating methods fail the build, not a review.
**Testing**
- Start a real `LocalRouter(port=0)` (`async with LocalRouter(port=0) as router:`), mount the service on `Mesh(router)` (`mesh.mount(svc)` and `async with mesh.serve():`), and call it through the generated client (`ChatClient(mesh)`): this exercises routing, validation, streaming and error mapping end to end.
- Assert on error *classes* and `details`, not message text.
## Operate
- Router binary: it ships inside the SDK packages (platform wheel / npm
platform package), so nothing to install; `meshcall-router --port 8765`
runs it. `uv run meshcall router install` only matters on a platform
without a bundled binary.
- Agent skill installation: `meshcall init [--agent universal|claude|cursor|copilot|windsurf|all] [--force]`
writes `.agents/skills/meshcall/SKILL.md` and `AGENTS.md` by default, or
the agent-specific skill/rule files (`CLAUDE.md`, `.cursor/rules/meshcall.mdc`,
`.github/copilot-instructions.md`, `.windsurf/rules/meshcall.md`) when
`--agent` is specified.
- Rolling restart: draining a `Mesh` (`mesh.run()` on `SIGTERM`, or `await mesh.drain()`)
leaves the pool first, so no request fails. Restarting a Router: send it
SIGTERM; it refuses new calls with retryable `unavailable` /
`router_draining`, closes idle connections with 1001 so peers move to
another Router, and gives calls in flight `--shutdown-timeout` (default
10 s) before ending them with `unavailable` / `router_shutdown`.
- `--max-calls-per-connection` (default 1000, `0` unlimited) bounds one
connection's calls in flight; beyond it a call gets retryable
`resource_exhausted` / `overloaded`.
- Several Routers: give services and clients `Router([uri1, uri2])`; no
coordination is needed because the Router keeps no state peers cannot rebuild.
- Tunnels (one instance for one caller, e.g. a person's browser to their dev
container): the instance opts in at mount (`accept_tunnels=True` or a
`(TunnelOffer) -> bool` hook, `on_tunnel_closed=`; TS `acceptTunnels` /
`onTunnelClosed`; Go `WithAcceptTunnels` / `WithTunnelClosed`) and reads
the caller from `ctx.tunnel` (id, principal), never from metadata; an
issuer account or API key calls `mesh.tunnels.open(instance=…, scopes=…,
principal=…)` and hands the `mtun_…` credential to the client, which
connects with `Mesh(router, tunnel=cred)`. Targeted clients are
constructed with the tunnel's instance id. Bind registration credentials with
`instance_ids` so nothing can impersonate the instance. When the Router
must not read the traffic, seal it end to end: give the instance a key
pair once (`generate_e2e_key()` / `generateE2EKey()` /
`meshcall.GenerateE2EKey()`; serve with `e2e_private_key=` /
`{ e2ePrivateKey }` / `WithE2EPrivateKey`), have the issuer pin its public
key in `tunnels.open(..., e2e_key=…)` and hand it to the client with the
credential (`Mesh(router, tunnel=cred, e2e_key=pub)`, `{ tunnel, e2eKey }`,
`WithE2EKey`). Never take the key from the Router. E2E credentials start
with `mtun_e2e.` and need the key (a Mesh refuses one without it); add
`require_e2e=True` (`requireE2E` / `WithRequireE2E()`) at mount so plain
tunnels to those services are refused. Python needs `meshcall[e2e]`;
`ctx.tunnel.sealed` tells the service. When the instance itself must decide
who connects (a device serving only clients its owner paired), give each
client its own key: `Mesh(..., e2e_identity=E2EIdentity(private_key,
instance_id, pairing=E2EPairing(id, psk)))` (`{ e2eIdentity }` /
`WithE2EIdentity`); the device shows the pairing id and a one-time PSK
(`generate_e2e_psk()`) out of band, never through the Router. Mount with
`authorize_e2e_peer=` (accept known keys; spend the pairing only when
`peer.pairing_id` is set), `e2e_pairing_psk=` and `require_e2e_peer=True`
(`requireE2EPeer` / `WithRequireE2EPeer()`), which refuses every call
outside an authenticated session, tunnelled or not
(`permission_denied` / `e2e_peer_required`); handlers read `ctx.e2e.peer_key`.
- Configure the Router with flags or `MESHCALL_ROUTER_<FLAG>` variables
(`MESHCALL_ROUTER_PORT`, `MESHCALL_ROUTER_IDLE_TIMEOUT`, …); put accounts in
`MESHCALL_ROUTER_AUTH` (the auth JSON itself) or `MESHCALL_ROUTER_AUTH_FILE`.
Callers without credentials are the `anonymous` user (grant it `call`
rules in the auth file for public methods); give machine callers API keys
(`meshcall-router new-api-key ID`, sent as `Authorization: Bearer mk_…`).
`--max-connections` (default 10000) caps WebSocket connections (HTTP calls
are not counted); over it new connections get a retryable `503`.
One payload or stream item must fit in a frame: `--max-frame-size`
(default and maximum 64 MiB); send larger data as a stream.
`--outbox-size` (default 256 MiB, at least the frame size) is how much a
peer that stops reading may be owed before the Router disconnects it.
For multi-node edge clusters backed by etcd, configure `--cluster-etcd`,
`--cluster-listen`, and `--cluster-key-file` (or `MESHCALL_ROUTER_CLUSTER_KEY`).