@kolu/surface-mcp reference
Re-expose a @kolu/surface rooted bundle as an MCP server, so a coding agent drives it
with structured tool calls. The adapter owns the resources/subscribe lifecycle, stdio discipline and the framework’s
Effect Schema → JSON-Schema bridge. You choose what is exposed.
The server
A bundle is an unprefixed core surface, keyed sibling surfaces, or both. One call serves it and answers a handle you
re-roster and close.
| Export | Subpath | What it is |
|---|---|---|
serveSurfaceAsMcp | . | Serves a rooted bundle as an MCP server. |
served.reroster(surfaces) | . | Replaces the sibling map whole, on a running server. |
OwnedSurfaceConnection | . | The dialled connection the adapter owns, and how it learns the link died. |
serveSurfaceAsMcp
// The face composes on a ROOTED BUNDLE — an unprefixed `core` beside a keyed set
// of `surfaces`. One surface is the degenerate bundle: a core and no siblings,
// whose names are the bare `surface://cells/<key>` and `<ns>_<verb>`.
const { server, close } = await serveSurfaceAsMcp({
core: {
surface,
expose: {
/* … */
},
},
client: () => ({ core }),
});
serveSurfaceAsMcp(opts): Promise<ServedSurfaceMcp>, imported from the root @kolu/surface-mcp subpath. It answers
{ server, reroster, close }.
| Option | Meaning |
|---|---|
core? | The unprefixed root, { surface, expose }. Its members keep their bare names. |
surfaces? | The siblings, keyed: { [key]: { surface, expose, tools? } }. Each key becomes a segment of every name that sibling contributes. |
client | A factory () => bundle for a live implementation. See the client factory. |
tools? | Hand-authored bespoke tools at the bundle root. They are bare-named, and handed the whole bundle. |
serverInfo? | MCP server identity. |
instructions? | The server’s own initialize instructions. See instructions. |
transport? | Defaults to StdioServerTransport; inject an in-memory half for tests. |
- A bundle with neither a core nor a sibling is refused at boot.
- A single surface is the degenerate case: a
coreand no siblings. Every name it mints is the bare one.
instructions
Where an embedding app teaches an agent its domain (“everything here is about nodes, not files”).
- A string is handed to the SDK’s
Serverbare, which answersinitializeinside its ownProtocol. - A function
() => stringis read at eachinitialize: once per host connection, on the request path, never at construction. A bundle whose roster moves composes the text from the rows standing when a host asks. - An empty result is no
instructionskey, as the SDK already does for an empty string. - The function arm registers its own
initializehandler and calls through toServer’s private_oninitialize(@modelcontextprotocol/sdk1.29.0) for version negotiation and the client-capability capture, overlaying only this field. The string arm never touches it. - What a roster move reaches is under
served.reroster(surfaces).
The client factory
client is a factory () => bundle for a live implementation.
- Return an
OwnedSurfaceConnection({ client, dispose, onClose? }) when the adapter owns a dialled socket. Return the bareRootedSurfaceClientsbundle when there is nothing to dispose. - It is re-invoked on retry after a drop, and after every
reroster, so it must read the host’s current roster rather than close over one.
Two shapes:
- Serve fresh:
clientisbuildSurfaceFace(surface, directDispatch(runtime))over an in-processimplementSurface. The MCP server is the surface’s backend. - Bridge a live surface:
clientdials an already-running served surface over a socket or ssh stdio. The MCP server is a face on an existing server (odu’sodu mcpdials.ci/odu.sock).
served.reroster(surfaces)
served.reroster(surfaces) replaces the sibling map whole: what is absent from the argument has left. The core does not
move. It is the member of every generation this endpoint can serve, and serving a different core is a different
endpoint. connectSurfaces.redial
leaves its root alone for the same reason.
A move:
- re-runs the whole boot composition, so a roster the gate would refuse leaves the endpoint exactly as it was;
- re-dials
client(), so the bundle carries the arriving siblings’ clients; - ends any
resources/subscribethe new roster cannot serve, and re-opens the survivors’ on the new connection; - sends
notifications/tools/list_changedandnotifications/resources/list_changed; - reaches the next host’s
instructions, and only the next.
A function-valued instructions is read at each initialize, so a host that connects after the move is told the roster
it gets. A host already connected keeps what it was told, as MCP has no instructions_changed notification. reroster
takes no text of its own: the thunk is how the roster reaches initialize.
The face advertises tools: { listChanged: true } and resources: { subscribe: true, listChanged: true } from the
first initialize, so a host knows the lists can change and re-reads them.
Calling a name a past roster served
A call to a name a past roster served and this one does not is refused by name, never a bare “unknown”. The refusal says which of the two retirements it was, because the caller’s next move differs:
- the sibling left: the sentence
SurfaceSiblingDroppedgives a caller on the wire; - the sibling is standing and no longer exposes it: its roster entry narrowed.
A tombstone outlives its sibling’s return, so it survives that return’s own departure as well.
Why: Why a refusal names what failed.
OwnedSurfaceConnection
The bridge shape returns { client, dispose, onClose? }. The adapter memoizes one connection for reads and bespoke
tools, so it needs to know when that connection dies. There are two ways it finds out.
| Field | Meaning |
|---|---|
client | The live face the adapter dispatches over. |
dispose | Closes the transport the factory opened. The adapter calls it on teardown and before every re-dial. |
onClose? | Subscribes to this transport dropping. It fires at most once. |
- Supply
onClosewhenever the dial can reach its transport’s close. The adapter then discards the dead connection the instant it is announced, so the next request dials fresh. - Omit it only where there is nothing to announce. The in-process
directDispatchcase has no transport at all.
Without onClose
The fallback is discovery-by-failure: the adapter finds out the socket died by spending a request on it, in the read and tool catch path.
- The first request after every restart of the served daemon fails, and every later one succeeds.
- That message names the link (“stdio transport closed … the peer process exited”), which an agent reads on its own stdio channel as the MCP server dying.
- An absent
onClosestates that this connection carries no close announcement, either because the transport has none to give or because the dial does not project one it could. It is not a tuning knob. kolu mcp --hostis the second case: the ssh layer observes its child’s exit, butAgentDialhas no field to carry it. That is a gap in the dial’s face, not a limit of ssh.- Why: Why a refusal names what failed.
A transport death in flight
A socket can die with a request already in flight. That failure is re-framed before it reaches the host.
- The message names the dropped connection, confirms the MCP server is still running, and says the next request re-dials.
- Nothing is replayed, because a retried mutation against a fresh daemon generation would be a new defect.
- A call cut off in flight has an unknown outcome, not an undone one. The served side may have acted and only the reply been lost, and the adapter never decides that for the host.
A connection that is born dead
A transport can announce its close during registration, synchronously or on a microtask. The adapter re-checks the slot by identity after each dial, and re-dials rather than hand out a corpse, bounded, then fails loudly. Re-dialling is legitimate where re-requesting is not: a dial carries no caller intent, so repeating one replays nothing.
The projection
expose is default-deny: nothing crosses to the host until named. Every key is checked against its own surface’s spec
at boot, one map per surface, exactly as
exposeRootedFaces takes them. There is no composed top-level
spec.
| Surface member | Exposed as | URI / wire name (core) | …on sibling t |
|---|---|---|---|
| cell | resource | surface://cells/<k> | surface://cells/t/<k> |
| collection | resource (+ template) | surface://collections/<k> · …/<k>/{+id} | surface://collections/t/<k> · …/t/<k>/{+id} |
| stream | resource | surface://streams/<k> | surface://streams/t/<k> |
| event | resource | surface://events/<k> | surface://events/t/<k> |
procedure "<ns>.<verb>" | tool | <ns>_<verb> (. is illegal in a tool name) | t_<ns>_<verb> |
Resources are readable and subscribable; procedures become callable tools.
| Entry | What it covers |
|---|---|
| How a tool name is spelled | Which character of a procedure’s name becomes _, and which stays. |
Where ExposeMap lives | The package that owns the map, and the part this one owns. |
| Sibling prefixes | How a sibling key becomes a segment of every name it contributes. |
| How a collection item is addressed | Where an item’s name starts, which spellings name it, and how an address that serves nothing is refused. |
| What the composition refuses | The three refusals made at boot and on every reroster. |
| Which client a bespoke tool receives | The client handed to a sibling’s tools and to the bundle root’s. |
How a tool name is spelled
Only the separator becomes _. A namespace that itself contains a dot keeps it: procedures: { "a.b": { c } } mints
the tool a.b_c, not a_b_c.
- The tool name has to be reversible to one
(ns, verb)pair, and rewriting every dot would makea.b·canda·b.cthe same tool. - It is odd enough on a host’s tool list to be worth knowing before you meet it.
Where ExposeMap lives
The ExposeMap shape is not this package’s. It lives in
@kolu/surface/expose and is imported from there. There is no
re-export, because the wire faces (serveSurfaceApp, serveOverUnixSocket) take the same map.
What stays here is the resolver: only this adapter turns a map entry into a surface:// URI or an MCP tool name. A
consumer gating its MCP face and its browser face writes one kind of map, and the same key means the same thing on both.
Sibling prefixes
The sibling key is a segment of the URI and of the tool name, and the core is the only surface without one. It is the
rule composeSurfaceContracts applies to wire tags, applied here to MCP’s
two name spaces.
- Two siblings exposing the same member key are therefore disjoint, rather than merged.
- Every name a sibling contributes takes the segment, its hand-authored
toolsexactly as its generated names do (outlines_read), so a reader of atools/listnever has to know which kind of name they are looking at. - A sibling’s tool word is row-relative (
read,commit,nodes), the same word the argv face puts the row’s own subcommand in front of. - Only the bundle-root
toolsstay bare, having no row to be relative to. - A tool name is not reversible to its origin.
_is legal inside a tag segment, sooutlines_ops_runcan be spelled by more than one(sibling, ns, verb)triple. Which sibling owns a tool is recorded on its entry, which is what the departed-name refusal consults. - What guarantees the namespace is the one-pass collision check over the finished names. The prefix narrows what can reach that check.
- Why: Why each face spells a name its own way.
How a collection item is addressed
An item of collection <k> is read and subscribed to at the collection’s address, a /, and the item’s name:
surface://collections/<k>/<name>, or surface://collections/t/<k>/<name> on sibling t.
- The name is everything after the collection’s address, so it may contain
/. A kolu terminalremote:box/9ab1is read atsurface://collections/terminals/remote:box/9ab1. - The name is percent-decoded once:
a/b,a%2Fbanda%2fbname the same item. A literal%is written%25, and nothing else needs escaping. - The advertised template is
…/<k>/{+id}. An RFC 6570 host expands{+id}with/and:left as they are, so the address it writes is the one a person would. - An empty name, or one that is not valid percent-encoding, addresses nothing.
- The name is decoded through the collection’s key schema, so a
Schema.Finitecollection reads…/rows/42as42. - An answer carries the address you asked at. A subscription is kept under the address it was made at, so two spellings of one item are two subscriptions, each notified at its own address.
An address this endpoint does not serve is refused on resources/read and resources/subscribe alike, in one of three
sentences:
| The address | The refusal says |
|---|---|
| belonged to a sibling that left, or that no longer exposes it | that it is no longer served, and which of the two |
| falls under a served collection, and the name fails the collection’s key schema | that it names no item of that collection, then the key schema’s own failure message |
| is anything else | unknown resource, then every static resource address and every item template the endpoint serves |
What the composition refuses
Three refusals, each made at boot and again on every reroster:
- a sibling key that equals a core collection’s key is refused:
surface://collections/<k>/{+id}would be that collection’s items and that sibling’s whole address space, and no lookup order resolves that honestly. With it held, no served collection’s address is a prefix of another’s, which is what lets an item’s name contain/; - the whole tool namespace, generated names plus every bespoke table, is checked for duplicates in one pass, each candidate tagged by origin, so a report names both claimants;
- a
exposekey that names nothing on its own sibling’s spec is refused where it is written.
Prefixing does not make the duplicate check redundant. The bundle-root table is bare and shares one space with every
scoped name, so a root a_here beside a sibling a’s here is refused, as is a root a_ops_run beside a sibling a
exposing ops.run.
Which client a bespoke tool receives
A bespoke tool receives the client of the thing it is declared on.
- A sibling’s
toolsare handedclients[key]. - The bundle-root
toolsare handed the whole{ core, clients }bundle. - A root-level verb that wants only the core reaches
client.core, which says which surface it is about at the line that calls it.
Bespoke tools and curation
Hand-authored, call-shaped capabilities (spawn-and-wait, blocking polls) sit beside the generated ones, and
projectSurface curates what a generated face shows at all.
| Export | Subpath | What it is |
|---|---|---|
tools: | . | The hand-authored tool record, on a sibling or at the bundle root. |
projectSurface | @kolu/surface/project | Projects a live surface into an observer-safe second surface to serve. |
tools:
Each entry is { description, title?, input: Schema.Struct(...), mutates, handler, render? }.
handler(args, client, signal)composes over the live client, and still rides the JSON-Schema bridge and lifecycle.- A scalar, array, or union input is advertised wrapped under
value, and unwrapped before decode. titleis MCP’s display name. A host that has none rendersname, the machine spelling.titleanddescriptionare bespoke-only:ToolExposurehas no field for either, so a procedure-derived tool carries neither.render?: (out) => ToolResultoverrides how the success value becomes content. It is declared per tool rather than sniffed per result, so a handler cannot change its own content type call-to-call, and the dispatch never guesses from a value’s shape. Its one use is an answer that is a picture.
Failure framing
A rejecting handler always returns an isError tool result, never a JSON-RPC protocol error, so the agent sees a typed,
retryable failure instead of its SDK throwing. A failing procedure call does the same, including the bridged transport
going down mid-call.
One tool namespace
Generated (<ns>_<verb>) and bespoke names, across the core, every sibling and the bundle root, are checked for
collision in one pass at boot and on every reroster. Each candidate is tagged by origin, so the error names both
sources.
projectSurface
projectSurface (from @kolu/surface/project) is the cleanest curation. Project the live surface into an
observer-safe second surface, dropping dangerous procedures, bounding logs and deriving verdicts, and serve that.
Tool results
Every successful result carries data in structuredContent. Every tool that answers in words also carries prose in
content, so an agent acts on the value and never parses the sentence.
- Both arms are read off one serialization, so they cannot disagree. That is also what keeps a value that is an object
in memory and a string on the wire (a
Date) from publishing astructuredContentthat is not an object. - MCP types the structured arm as a JSON object, so a scalar, array or
nullanswer travels under the same singlevalueproperty a scalar input is wrapped in.
| Entry | What it covers |
|---|---|
The value wrapper on each side | Where the input’s wrapper and the result’s agree, and where they diverge. |
| What carrying both arms costs | The frame a doubled answer measures, and where to bound it. |
ToolFailure | The refusal that carries a structured detail beside its message. |
| Failures without a structured arm | What every other failure reaches the host as. |
| When the answer is a picture | render: okImage(...), and the copy a caller must not make. |
The value wrapper on each side
The same key is decided independently on each side: the input from its declared schema, the result from the value on
the wire. They agree for every scalar, array and null. They diverge in one place:
- a union input has no top-level
type, so it is advertised wrapped, and the host sends{ "value": { "a": 1 } }; - the same object as an answer is already an object at runtime and travels bare,
{ "a": 1 }.
A caller therefore cannot recover, from a result alone, whether a { "value": 42 } it received was the tool’s own
object or a wrapped scalar 42. Wrapping every result would close that, at the price of changing the shape of every
success this adapter emits.
What carrying both arms costs
Carrying the answer twice roughly doubles the frame of a large result. A full 10k-row terminal scrollback measures
1.2 MB before and 2.4 MB after. That is the price of MCP’s own back-compat guidance that a server returning
structuredContent should also return equivalent text. A tool that can return an unbounded payload should bound it at
the tool, not by dropping an arm.
Why: Why a tool result is carried twice.
ToolFailure
A refusal is an answer, and it can carry the structured arm too. Fail with a ToolFailure and the message reaches the
model while the detail reaches the caller:
import { ToolFailure } from "@kolu/surface-mcp";
Effect.mapError(refusal, (f) =>
new ToolFailure(`set_done was refused (${f.kind}): ${f.message}`, {
kind: f.kind,
blocking: f.children,
}));
- The message is branded with the adapter’s name on the way out (
surface-mcp: …), as any other failure it reports is. - The detail goes through the same JSON round-trip and object-wrapping the success arm does, so a refusal cannot publish
a shape a success would have been refused for. A
Datein a detail arrives as its ISO string, and a detail JSON renders as a non-object rides undervaluelike any other non-object answer. ToolFailureis generic in its detail (ToolFailure<D>), so a consumer’s own refusal union survives to the place it is asserted on instead of widening toRecord<string, unknown>at construction.- The discriminant is
instanceof. That is sound because the package is private and every consumer resolves the one workspace copy. - A failure raised on the far side of a surface hop is not a
ToolFailure. A handler that wants such a refusal structured catches it and re-raises it as one.
outputSchema is coupled to structuredContent
No tool advertises an outputSchema, and adding one is not free.
- An MCP client validates
structuredContentagainst a declaredoutputSchemawhenever the field is present, including on anisErrorresult. - A refusal’s detail is a different shape from the success it refused, so a success-only schema would make every structured refusal throw inside the client instead of reaching the agent.
- Whoever adds
outputSchemaowes the refusal shape a home in it first.
Failures without a structured arm
Every other failure is message-only, with no structuredContent at all. Structuring whatever an error happens to hold
would publish a Data.TaggedError’s stack into the agent’s data channel, and dress an incidental TypeError up as a
contract. The adapter still describes such a failure:
- a tagged error whose identity is
_tagand whosemessageis empty reaches the host as its tag; - a non-
Errorfailure value reaches the host as its JSON.
When the answer is a picture
A tool whose answer is pixels declares render: okImage(...) and returns an MCP image content block instead of prose.
okImage(image, detail)puts the bytes incontentexactly once, and the facts about them (mime type, dimensions) instructuredContent, through the same normalization every other result uses.- The payload is not repeated as text, and not smuggled into
detail. A host renders the image, so a second copy spends a megabyte of the model’s context window and is a second place for the answer to be wrong. - That rule is a contract the caller keeps, not a check:
okImagedoes not inspectdetailfor the bytes, so a copy such asdetail.data = image.data.slice()passes straight through. The cost is invisible at the call site and enormous on the wire. ToolContentis the resulting union:{ type: "text" }or{ type: "image", data, mimeType }.- kolu’s
screen_image(a terminal’s screen as a themed PNG) is the in-tree consumer. - Why: Why a tool result is carried twice.
The schema bridge
Effect ships the converter (Schema.toJsonSchemaDocument, draft 2020-12, the dialect MCP standardized on). What this
package owns is the adapter glue, and the tools/list JSON Schema it produces is read by Anthropic, Gemini, Bedrock,
Codex and Claude Desktop. Effect’s converter diverges from the zod one in ways an agent would notice, so
toInputSchema:
- reopens every object, because Effect emits
additionalProperties: false, which is an outright host break; - normalizes
Schema.Number’s Infinity/NaN-tolerant union back to its numeric arm; - special-cases
Schema.VoidandSchema.Undefined, so a no-arg tool does not end up demanding{"value": null}.
Why: Why the schema bridge belongs to the framework.
Writing a schema for an MCP-facing tool
Two authoring rules follow:
- Prefer
Schema.FiniteorSchema.Intfor an MCP-facing numeric. They emit{"type":"number"}and{"type":"integer"}outright, the integer with the safe-integerminimum/maximumthatisInt()enforces. - Put a
defaultannotation on the encoded-side node, insideoptionalKey.withDecodingDefaultKeyis a transformation the encoded document cannot see through, so a default declared outside it never reaches the agent.
Other exports
| Export | Subpath | What it is |
|---|---|---|
toInputSchema(schema?) | . | Effect Schema → JSON Schema, re-exported from the framework. |
resolveExpose(spec, expose, sibling) | . | The default-deny resolver for one surface. |
resolveBundle(bundle) | . | The whole-bundle resolver that boot and every reroster run through. |
servesAddress(uri, generation) | . | Whether a resolved bundle serves an address, for a read and a subscription alike. |
scopedToolName(sibling, name) | . | The tool-name half of the prefix rule (t_ops_run). |
McpCore<S> · McpSibling<S> · McpBundle<C, M> | . | The bundle’s option shapes. |
SiblingKey | . | A sibling’s key, re-exported from the framework’s client subpath. |
ToolFailure<D>(message, detail) | ., /tools | The refusal a handler fails with when the reason is machine-readable. |
messageOf(error) | ., /tools | The framework’s “name what broke” derivation, re-exported. |
okImage(image, detail) | ., /tools | Wraps a tool result whose answer is an image. |
BespokeTool | ., /tools | The framework’s verb record, extended with render. |
ToolInputSchema | ., /tools | The framework’s SurfaceVerbInputSchema under this package’s name. |
ToolResult · ToolContent · ServeSurfaceAsMcpOptions · ServedSurfaceMcp · ResolvedBundle · ResolvedBespokeTool | . | Types. |
SurfaceClientCallable · RootedSurfaceClients · OwnedSurfaceConnection · PusherConnection<Client> | . | Types, re-exported from the framework’s client subpath. |
toInputSchema(schema?)
Effect Schema → JSON Schema (draft 2020-12), $ref-dereferenced, top-level-object enforced. It is a re-export of
@kolu/surface/verbs: the bridge is the framework’s,
shared with the CLI face.
resolveExpose(spec, expose, sibling)
The default-deny resolver for one surface. It answers { resources, resourceTemplates, tools }, with sibling folded
into every name it mints. sibling is required, and undefined names the bare core: it is the address, not an omitted
argument.
resolveBundle(bundle)
The whole-bundle resolver that the boot and every reroster run through. It answers:
- the flat tables;
- the indices over them (
byUri·templateByCollection·toolByName); - the three list answers projected once per generation (
advertisedTools·advertisedResources·advertisedResourceTemplates); - every refusal the composition owes.
It is one value, replaced whole by a move, so no request ever reads a half-updated roster.
servesAddress(uri, generation)
Whether generation, a resolveBundle result, serves uri.
- It asks the reader
resources/readandresources/subscriberesolve through, with no client and no request. - A consumer that states its own addresses checks them with it, rather than with a router of its own. kolu’s Conductor script is checked this way.
scopedToolName(sibling, name)
The tool-name half of the prefix rule (t_ops_run). It applies to a sibling’s hand-authored tools as well as its
generated ones.
McpCore<S> · McpSibling<S> · McpBundle<C, M>
The bundle’s option shapes.
SiblingKey
Re-exported from @kolu/surface/client, where it
lives beside clientAt. Both projecting faces read the same one.
messageOf(error)
The framework’s “name what broke” derivation
(@kolu/surface/errors), re-exported here under
the name this package shipped it with. It is the one the request edge uses to word a failure.
Reach for it in a bespoke tool that folds a caught failure into its own message instead of raising it, so both paths
word the same error the same way. It handles the two shapes e instanceof Error ? e.message : String(e) gets wrong: a
tagged error whose message is empty, and a failure declared as a plain object.
BespokeTool
The framework’s SurfaceVerb, the record an app
hands to every face verbatim, so the same table also projects as argv through @kolu/surface-cli. This package extends
it with the one field only this face can act on, render.
ToolInputSchema
The framework’s SurfaceVerbInputSchema under the name this package shipped it with.
SurfaceClientCallable · RootedSurfaceClients · OwnedSurfaceConnection · PusherConnection<Client>
Types, re-exported from
@kolu/surface/client: the client shape a
projecting face holds, the bundle of them a rooted face dials, and the connection it owns. OwnedSurfaceConnection is
the framework shape at this adapter’s client type, and the CLI face aliases the very same one, so a host can write one
connection factory that feeds both.
The @kolu/surface-mcp/tools subpath
@kolu/surface-mcp/tools is a subpath of its own: the BespokeTool / ToolInputSchema / ToolFailure / okImage /
messageOf spine that the root barrel re-exports. Importing it costs zero MCP SDK imports, carrying the verb record and
Schema vocabulary with no server class and no transport.
A binary whose command tree is static hands its one table to both faces: MCP via the root barrel, shell argv via
@kolu/surface-cli. Every --help then runs without loading a server it never boots. kolu
is the first-party proof. kolu-mcp owns its KOLU_MCP_TOOLS in a leaf that imports only this subpath, and the
kolu surface argv face statically holds that leaf on every kolu --help.
Why: Why the schema bridge belongs to the framework.
Not exported here
ExposeMap and ToolExposure are not exported by this package. Import them from
@kolu/surface/expose, their one home.
The step-by-step is in How to expose a surface to agents.