44. MCP
The daemon of chapters 40 to 43 runs tools compiled into it and code the model writes, in a sandbox. This chapter gives it the Model Context Protocol, at revision 2026-07-28, in both directions: tools that live in another process are mounted into every session’s tool set, and the daemon’s own tools are offered to another harness. The code is internal/mcp (the messages, the client, Mount, the server’s Handle), internal/mcp/stdio and internal/mcp/streamable (the two transports), the daemon’s mcp.go, and aecd mcp.
Why this layer exists
Every tool the book built before this chapter was compiled into the binary that called it: chapter 27’s agent.Tool is a Go value, and chapter 36’s skills are inert text on purpose. A daemon that is a peer of other harnesses rather than a wrapper around one needs the opposite in both directions. Tools that live elsewhere (a database’s, a browser’s, the reader’s own scripts) have to be mountable into a session without being recompiled in. The daemon’s own tools (its workspace, its memory, its sandbox) have to be offerable to a harness that launches subprocesses. MCP is the protocol both directions now share, and at this revision it is small enough to implement from the specification in one chapter: JSON-RPC 2.0 messages, three methods a tool server must answer, two transports, and a set of MUSTs a conformance suite can enumerate.
Hermes does the client half with the mcp SDK, driven from tools/mcp_tool.py. At commit cca83848ec79a4a6a2ecc10285725559bf72c97c that file opens by connecting “the mcp_servers configured in ~/.hermes/config.yaml (stdio, Streamable HTTP or SSE)” (mcp_tool.py:1–3), pins LATEST_PROTOCOL_VERSION = "2025-03-26" as a fallback and says the handshake from 2026-07-28 on “is a per-request envelope so this can be OLDER than LATEST_PROTOCOL_VERSION” (:75–80), and still captures the result of await session.initialize() (:430). It is a dual-era client, carrying the code for the handshake this revision removed. The client here is modern-only, and the cost is stated where it is paid: a server that needs initialize cannot be mounted, and Client.Discover says so by name.
Four things this chapter does not do, and the chapter that owns each. It answers no input request: a server that wants to ask the principal something (revision 2026-07-28 calls the pattern Multi Round-Trip Requests, MRTR) is explained and refused, and chapter 47 decides whether a principal may be asked through a gateway. It brokers no OAuth; chapter 48 discusses it and does not build it. It vets no server: Trust is the hook, and chapter 48 is where a server earns the word (the daemon honours trusted only against a lock that aecd vet mcp -write stored, and this chapter’s daemon, which did not have the lock, trusted a configured server as configured). And it runs no third-party server. Every server in this chapter is this book’s, so everything the conformance suite shows is that this implementation agrees with this book’s reading of the specification. A misreading shared by the code and the fixtures, which one author wrote from one text, is invisible to both, and interoperability with another implementation is not measured here.
Mechanism
Messages, and the id that may not be null
A JSON-RPC 2.0 message is one of four shapes: a request (a method and an id), a notification (a method and no id), a result (an id and a result), an error (an error, and the id of the request that failed). MCP tightens three things (basic/index, “Messages”). “Unlike base JSON-RPC, the ID MUST NOT be null.” The id is a string or an integer, and a request’s must not match “the ID of any other request the sender has issued and not yet received a response for”. A result “MUST include a resultType field”, of which complete and input_required are the two the core protocol defines; a client treats an absent one as complete and any other value as invalid.
// ProtocolVersion is the one revision this implementation speaks (D5). A
// server that does not support a request's version answers
// UnsupportedProtocolVersion with the list it does; this client never falls
// back to the initialize handshake of 2025-11-25 and earlier.
const ProtocolVersion = "2026-07-28"
// JSONRPCVersion is the only value the jsonrpc field may hold.
const JSONRPCVersion = "2.0"
Classify is the decision table. Which of the four shapes a Message is follows from which fields it carries, and TestClassify pins the thirteen combinations below, plus two ids (a fraction, a boolean) that do not decode at all.
| The message | Classify |
|---|---|
{"jsonrpc":"2.0","id":1,"method":"x"} |
request |
{"jsonrpc":"2.0","id":"a","method":"x","params":{}} |
request |
{"jsonrpc":"2.0","method":"x"} |
notification |
{"jsonrpc":"2.0","id":null,"method":"x"} |
invalid |
{"jsonrpc":"2.0","id":1,"result":{"resultType":"complete"}} |
result |
{"jsonrpc":"2.0","result":{}} |
invalid |
{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"m"}} |
error |
{"jsonrpc":"2.0","error":{"code":-32700,"message":"m"}} |
error |
{"jsonrpc":"2.0","id":1,"result":{},"error":{"code":1,"message":"m"}} |
invalid |
{"jsonrpc":"2.0","id":1,"method":"x","result":{}} |
invalid |
{"jsonrpc":"1.0","id":1,"method":"x"} |
invalid |
{"id":1,"method":"x"} |
invalid |
{} |
invalid |
The null id is forbidden for a reason JSON-RPC itself supplies. JSON-RPC uses a null id in the error reply to a request whose id could not be read, so a request that carried a null id would make its own error unaddressable: the reply would be indistinguishable from the reply to garbage. encoding/json cannot see the difference between "id": null and no id at all (both leave a nil pointer), so Message.UnmarshalJSON is hand-written and keeps them apart: an ID has a Set flag and an IsNull flag, an absent id is a nil *ID on the message, and Classify refuses a request whose id is set and null.
That function does three more things, each a defence rather than a convenience. It reads members by exact name, because JSON-RPC member names are case-sensitive ("Method" is not "method"), where encoding/json folds case. It refuses a member name that appears twice. And DecodeMessage refuses any data after the first value, a stray ] or } included. The first two exist for one attack, which the HTTP section meets: two decoders that disagree about which occurrence of a repeated key wins, or which spelling of a key counts, can read different bodies from the same bytes, and a check made by one then guards nothing that the other executes.
A reply to a message whose id could not be read is where the two documents disagree, and the code takes a side. JSON-RPC 2.0: “If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it MUST be Null.” MCP, in the base protocol’s “Error Responses”: error responses “MUST include the same ID as the request they correspond to (except in error cases where the ID could not be read due a malformed request)”, and the schema at the pinned commit types the member as optional (JSONRPCErrorResponse in schema.ts at 4a04acd, line 300: id?: RequestId), a type that has no null in it. A client that validates replies against the schema would reject "id": null. This code follows the schema, because the peers of an MCP implementation are MCP clients: Message.MarshalJSON omits an id that is null or unset, on every endpoint, the control socket included, and the client reads both forms. The cost is a strict JSON-RPC 2.0 client, which sees no id on a parse error. The first version of this code wrote null, on JSON-RPC’s authority alone, and a review that read the pinned schema found the disagreement; TestMessageOmitsAnUnreadableID and the fixtures for the three framing errors now pin the omission.
// ID is a JSON-RPC request id: a string or an integer (the schema's
// RequestId). MCP forbids null (basic/index#requests); a null id decodes
// with Set true and IsNull true so that Classify can refuse it, and an
// absent id is a nil *ID on the Message. A Message never writes a null id:
// a reply to a message whose id could not be read omits "id", as the MCP
// schema types it (JSONRPCErrorResponse.id is optional; JSON-RPC 2.0 says
// null; see Message.MarshalJSON).
type ID struct {
Str string
Num int64
IsStr bool
Set bool
IsNull bool
}
// String renders the id the way a log or an error message names it.
func (id ID) String() string {
switch {
case !id.Set, id.IsNull:
return "null"
case id.IsStr:
return strconv.Quote(id.Str)
default:
return strconv.FormatInt(id.Num, 10)
}
}
// Equal is identity on the wire: "1" and 1 are different ids.
func (id ID) Equal(o ID) bool {
return id.Set == o.Set && id.IsNull == o.IsNull && id.IsStr == o.IsStr && id.Str == o.Str && id.Num == o.Num
}
// Key is the map key a demultiplexer uses: the type is part of it.
func (id ID) Key() string {
if id.IsStr {
return "s:" + id.Str
}
return "n:" + strconv.FormatInt(id.Num, 10)
}
func (id ID) MarshalJSON() ([]byte, error) {
switch {
case !id.Set, id.IsNull:
return []byte("null"), nil
case id.IsStr:
return json.Marshal(id.Str)
default:
return json.Marshal(id.Num)
}
}
func (id *ID) UnmarshalJSON(b []byte) error {
id.Set = true
if string(b) == "null" {
id.IsNull = true
return nil
}
if len(b) > 0 && b[0] == '"' {
id.IsStr = true
return json.Unmarshal(b, &id.Str)
}
var n json.Number
if err := json.Unmarshal(b, &n); err != nil {
return fmt.Errorf("mcp: id must be a string or an integer: %w", err)
}
v, err := n.Int64()
if err != nil {
return fmt.Errorf("mcp: id must be a string or an integer, not %s", n)
}
id.Num = v
return nil
}
// StringID and NumID build ids.
func StringID(s string) ID { return ID{Str: s, IsStr: true, Set: true} }
func NumID(n int64) ID { return ID{Num: n, Set: true} }
// Message is any JSON-RPC 2.0 message on the wire: a request (Method and
// ID), a notification (Method, no ID), a result (ID and Result) or an
// error (Error, ID when it could be read). Params, Result and the error's
// Data stay raw: the method decides their shape.
type Message struct {
JSONRPC string `json:"jsonrpc"`
ID *ID `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
// Error is the JSON-RPC error object. Data is optional and method-defined
// (UnsupportedProtocolVersion carries {"supported": [...], "requested":
// "..."}). Message is the sender's text: Error() cleans and cuts it, so an
// error that is printed or logged cannot carry a terminal escape or a
// forged line.
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
func (e *Error) Error() string {
return fmt.Sprintf("mcp: %d %s", e.Code, Clean(e.Message, MaxErrorTextBytes))
}
// ShapeError is JSON that parses but is not a JSON-RPC message of this
// protocol: not an object, an id that is not a string or an integer, a
// member of the wrong type, or a member name that repeats. A server
// answers it with InvalidRequest (JSON-RPC: "the JSON sent is not a valid
// Request object"), where JSON that does not parse is ParseError. Its text
// names the member and never a Go type.
type ShapeError struct{ Reason string }
func (e *ShapeError) Error() string { return "mcp: " + e.Reason }
// MarshalJSON writes a message as the specification has it, with one
// departure from encoding/json's defaults: an id that is null, or set on
// nothing, is omitted. A reply to a message whose id could not be read
// (a parse error, an invalid request) carries no "id" because the MCP
// schema types the error response's id as optional (JSONRPCErrorResponse
// at 4a04acd: "id?: RequestId") and a client that validates against it
// rejects null. JSON-RPC 2.0 says the member "MUST be Null" there; this
// code follows the schema, which is the document its peers validate with.
func (m Message) MarshalJSON() ([]byte, error) {
type plain Message
p := plain(m)
if p.ID != nil && (!p.ID.Set || p.ID.IsNull) {
p.ID = nil
}
return json.Marshal(p)
}
// UnmarshalJSON reads a message by exact member name: JSON-RPC member names
// are case-sensitive, so "Method" is not "method", and a name that repeats
// is refused (two decoders that disagree on which occurrence wins are how
// a header check and an executor come to read different bodies). It keeps
// "id": null apart from an absent id, which encoding/json would not, and
// ignores members it does not know. A value that is not a message is a
// *ShapeError.
func (m *Message) UnmarshalJSON(b []byte) error {
dec := json.NewDecoder(bytes.NewReader(b))
tok, err := dec.Token()
if err != nil {
return err
}
if d, ok := tok.(json.Delim); !ok || d != '{' {
return &ShapeError{"a message is a JSON object, not a batch or a bare value"}
}
var out Message
seen := map[string]bool{}
for dec.More() {
kt, err := dec.Token()
if err != nil {
return err
}
key, _ := kt.(string)
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
return err
}
if seen[key] {
return &ShapeError{"the member " + strconv.Quote(Clean(key, 64)) + " appears twice"}
}
seen[key] = true
switch key {
case "jsonrpc":
if err := json.Unmarshal(raw, &out.JSONRPC); err != nil {
return &ShapeError{"jsonrpc is not a string"}
}
case "method":
if err := json.Unmarshal(raw, &out.Method); err != nil {
return &ShapeError{"method is not a string"}
}
case "id":
var id ID
if err := json.Unmarshal(raw, &id); err != nil {
return &ShapeError{"id must be a string or an integer"}
}
out.ID = &id
case "params":
out.Params = raw
case "result":
out.Result = raw
case "error":
if string(raw) == "null" {
continue
}
var e Error
if err := json.Unmarshal(raw, &e); err != nil {
return &ShapeError{"error is not an object with an integer code and a string message"}
}
out.Error = &e
}
}
if _, err := dec.Token(); err != nil {
return err
}
*m = out
return nil
}
// DecodeMessage decodes exactly one message from b: any bytes after the
// first value other than white space are an error (a trailing ']' or '}'
// included, which a decoder's More() does not report). A value that parses
// and is not a message is a *ShapeError; text that is not one JSON value is
// any other error.
func DecodeMessage(b []byte) (Message, error) {
var m Message
dec := json.NewDecoder(bytes.NewReader(b))
if err := dec.Decode(&m); err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return Message{}, fmt.Errorf("the message ends early")
}
return Message{}, err
}
if rest := bytes.TrimSpace(b[dec.InputOffset():]); len(rest) > 0 {
// Not a JSON text at all (RFC 8259: one value, then white space):
// a parse error, not a well-formed value of the wrong shape.
return Message{}, errors.New("the text holds more than one JSON value, or data after the first")
}
return m, nil
}
// The error codes: JSON-RPC's five, and the three the 2026-07-28 revision
// allocates in the sub-range -32020..-32099 it reserves for itself
// (basic/index#error-codes). Nothing else in that sub-range may be sent.
const (
ParseError = -32700
InvalidRequest = -32600
MethodNotFound = -32601
InvalidParams = -32602
InternalError = -32603
HeaderMismatch = -32020
MissingRequiredClientCapability = -32021
UnsupportedProtocolVersion = -32022
)
// Kind is what a Message is, decided by the fields it carries.
type Kind int
const (
KindInvalid Kind = iota
KindRequest
KindNotification
KindResult
KindError
)
func (k Kind) String() string {
switch k {
case KindRequest:
return "request"
case KindNotification:
return "notification"
case KindResult:
return "result"
case KindError:
return "error"
}
return "invalid"
}
// Classify applies the base-protocol rules (basic/index#messages): jsonrpc
// is "2.0"; a request has a method and a non-null string or integer id; a
// notification has a method and no id; a result has an id and a result and
// no error; an error has an error and no result, with an id that may be
// null or absent when the request's could not be read. Anything else is
// invalid, which a server answers with InvalidRequest and a client drops.
func (m *Message) Classify() Kind {
if m == nil || m.JSONRPC != JSONRPCVersion {
return KindInvalid
}
hasID := m.ID != nil && m.ID.Set && !m.ID.IsNull
nullID := m.ID != nil && m.ID.Set && m.ID.IsNull
switch {
case m.Method != "":
if m.Result != nil || m.Error != nil {
return KindInvalid
}
if nullID {
return KindInvalid
}
if hasID {
return KindRequest
}
return KindNotification
case m.Error != nil:
if m.Result != nil {
return KindInvalid
}
return KindError
case m.Result != nil:
if !hasID {
return KindInvalid
}
return KindResult
}
return KindInvalid
}
No handshake: _meta on every request
The 2025-11-25 revision opened every connection with an initialize exchange that negotiated a version and capabilities once, and the server remembered the answer for the life of the connection. Revision 2026-07-28 removed it (key change 2 in the changelog): “Every request now carries its protocol version and client capabilities in _meta”, and, in the base protocol’s “Statelessness”, “Servers MUST NOT rely on prior requests over the same connection to establish context (e.g., capabilities, protocol version, client identity)”. The sessions went with it (key change 1): servers “that need cross-call state use explicit, server-minted handles passed as ordinary tool arguments”.
// Meta is the _meta object of a request's params or a result. The
// io.modelcontextprotocol/ keys replaced the initialize handshake
// (changelog, major change 2): a request carries its protocol version and
// client capabilities every time, so a server needs no connection state
// (basic/index#statelessness). ProtocolVersion and ClientCapabilities are
// required on every request (schema RequestMetaObject); the others are
// optional. ServerInfo is what a result carries back.
type Meta struct {
ProtocolVersion string `json:"io.modelcontextprotocol/protocolVersion,omitempty"`
ClientCapabilities *Capabilities `json:"io.modelcontextprotocol/clientCapabilities,omitempty"`
ClientInfo *Info `json:"io.modelcontextprotocol/clientInfo,omitempty"`
ServerInfo *Info `json:"io.modelcontextprotocol/serverInfo,omitempty"`
LogLevel string `json:"io.modelcontextprotocol/logLevel,omitempty"`
SubscriptionID string `json:"io.modelcontextprotocol/subscriptionId,omitempty"`
ProgressToken json.RawMessage `json:"progressToken,omitempty"`
}
// The _meta key names, for the checks that name a missing one.
const (
MetaProtocolVersion = "io.modelcontextprotocol/protocolVersion"
MetaClientCapabilities = "io.modelcontextprotocol/clientCapabilities"
MetaClientInfo = "io.modelcontextprotocol/clientInfo"
MetaServerInfo = "io.modelcontextprotocol/serverInfo"
)
// Info is a subset of the schema's Implementation: name and version are
// required, title and description kept; websiteUrl and icons are not read
// or written (nothing here shows them).
type Info struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Version string `json:"version"`
Description string `json:"description,omitempty"`
}
// ListChanged is the {listChanged} object a capability holds.
type ListChanged struct {
ListChanged bool `json:"listChanged,omitempty"`
}
// Capabilities serves both directions: a client's (elicitation, extensions;
// roots and sampling are deprecated at this revision and never sent) and a
// server's (tools, resources, prompts, extensions). An empty object is a
// valid declaration meaning "nothing optional". It is a subset of the
// schema's ClientCapabilities and ServerCapabilities: resources.subscribe,
// experimental, logging and completions are neither read nor written, as
// nothing here uses them.
type Capabilities struct {
Tools *ListChanged `json:"tools,omitempty"`
Resources *ListChanged `json:"resources,omitempty"`
Prompts *ListChanged `json:"prompts,omitempty"`
Elicitation json.RawMessage `json:"elicitation,omitempty"`
Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}
The consequence the code rests on is that a server’s Handle is a function of one message and the server’s own configuration. It reads no connection and writes none. The same Server value therefore sits behind a subprocess’s stdin, a Unix socket and an HTTP handler, and the conformance fixtures call it with no transport at all. The costs are real and small. Every request carries its _meta: 112 bytes in the bare form the capture below sends, 179 with the clientInfo the daemon adds (counted by a script on wntrmute from the two strings), where the handshake paid its bytes once. A server that does need state across calls has to hand out a handle the model carries, and the handle is then input from the model, so the server validates it like any other. The same is true of MRTR’s requestState, which the specification calls “an attacker-controlled input” (mrtr, server requirement 4).
Handle checks a message in the order in which each check needs the fields the earlier one established.
| Order | Check | Answer |
|---|---|---|
| 1 | the message is a request (a notification gets no answer at all) | -32600 for an invalid message or a response |
| 2 | params is an object, _meta an object, the _meta members of the right type |
-32602 |
| 3 | the method is initialize |
-32601, the message naming the versions this server speaks |
| 4 | _meta carries io.modelcontextprotocol/protocolVersion |
-32602, data.field naming the member |
| 5 | _meta carries io.modelcontextprotocol/clientCapabilities |
-32602, data.field naming the member |
| 6 | the version is one the server speaks | -32022, data.supported and data.requested |
| 7 | the method | server/discover, tools/list, tools/call, the resources methods; else -32601 |
initialize is answered before the _meta checks, because a legacy client’s initialize carries no _meta: answering -32602 would tell it nothing it could show a person. The specification asks for the message (versioning, “Backward Compatibility with Initialization-Based Versions”): a server that supports only modern versions “SHOULD name the protocol versions it supports in any error it returns to an initialize request, on any transport: legacy clients have no fall-forward mechanism, and this message may be the only diagnostic they can surface to users.” Checking the method before _meta is how this server meets that SHOULD; the Walkthrough’s wire capture shows the answer to a legacy initialize.
server/discover is how a client learns what it is talking to without the handshake: it returns supportedVersions, the capabilities, optional instructions, and the server’s name in _meta (io.modelcontextprotocol/serverInfo), not in the result, which is why DiscoverResult.ServerInfo is a field Go never serialises (json:"-") and the client fills from _meta. It is also the probe that tells a modern server from a legacy one, and the specification is explicit that the test cannot be a single error code (stdio, “Backward Compatibility”): “The fallback MUST NOT be keyed to one specific error code: legacy servers respond to unknown pre-initialize requests with implementation-defined errors (commonly -32601 or -32602) or not at all.” What identifies a modern server is a modern error: the revision reserves -32020 to -32099 for itself (changelog, minor change 12), and Client.Discover has three outcomes. A result with supportedVersions is a modern server. An error whose code is one of the three the revision allocates (-32020 header mismatch, -32021 missing client capability, -32022 unsupported version) is also a modern server, refusing this request, and the caller reads data.supported. Anything else, an unknown method included, is ErrLegacy. -32601 and -32602 identify no era, since either could come from a server of either.
// Client is aec as an MCP client over one Transport. Every request it
// sends carries ProtocolVersion, Caps and Info in _meta; it keeps no
// session, because the protocol has none. ErrLegacy is what Discover
// returns when the server answers with anything but a DiscoverResult or a
// recognised modern error: the stdio compatibility rule says that is a
// legacy server, and this client does not fall back.
type Client struct {
T Transport
Info Info
Caps Capabilities
Version string // default ProtocolVersion
n atomic.Int64
}
// ErrLegacy names a server that needs the initialize handshake.
var ErrLegacy = errors.New("mcp: the server did not answer server/discover as a 2026-07-28 server would; it speaks an earlier revision with an initialize handshake, which this client does not implement")
// ErrInvalidResult is a result this client cannot read: an unknown
// resultType, or a shape the method does not allow.
var ErrInvalidResult = errors.New("mcp: invalid result")
// ErrListLimit is a tools/list walk that went over MaxTools or MaxListPages,
// or a cursor the server repeated.
var ErrListLimit = errors.New("mcp: the server's tool list is over this client's limits")
func (c *Client) version() string {
if c.Version == "" {
return ProtocolVersion
}
return c.Version
}
// NextID is the request id: a counter, never reused within the client's
// life, so no two open requests share one (basic/index#requests).
func (c *Client) NextID() ID { return NumID(c.n.Add(1)) }
// Request builds a request with the _meta fields filled in.
func (c *Client) Request(method string, params map[string]any) (Message, error) {
if params == nil {
params = map[string]any{}
}
meta := Meta{ProtocolVersion: c.version(), ClientCapabilities: &c.Caps}
if c.Info.Name != "" {
info := c.Info
meta.ClientInfo = &info
}
params["_meta"] = meta
b, err := json.Marshal(params)
if err != nil {
return Message{}, err
}
id := c.NextID()
return Message{JSONRPC: JSONRPCVersion, ID: &id, Method: method, Params: b}, nil
}
// Call sends one request and decodes a successful result into out,
// checking the base-protocol rules on the way: the response is a result or
// an error, its id is the request's, its resultType is one this client
// knows (absent reads as complete). A JSON-RPC error is returned as *Error.
func (c *Client) Call(ctx context.Context, method string, params map[string]any, out any) (resultType string, err error) {
req, err := c.Request(method, params)
if err != nil {
return "", err
}
resp, err := c.T.Call(ctx, req)
if err != nil {
return "", err
}
switch resp.Classify() {
case KindError:
// A reply to a request whose id the server could not read has no id
// (the schema) or a null one (JSON-RPC); both are accepted here.
if resp.ID != nil && resp.ID.Set && !resp.ID.IsNull && !resp.ID.Equal(*req.ID) {
return "", fmt.Errorf("%w: an error for id %s answered id %s", ErrInvalidResult, resp.ID, req.ID)
}
return "", resp.Error
case KindResult:
if !resp.ID.Equal(*req.ID) {
return "", fmt.Errorf("%w: a result for id %s answered id %s", ErrInvalidResult, resp.ID, req.ID)
}
default:
return "", fmt.Errorf("%w: the reply is %s, not a response", ErrInvalidResult, resp.Classify())
}
resultType, err = ResultTypeOf(resp.Result)
if err != nil {
return "", err
}
if out != nil {
if err := json.Unmarshal(resp.Result, out); err != nil {
return "", fmt.Errorf("%w: %s: %v", ErrInvalidResult, method, err)
}
}
return resultType, nil
}
// checkCacheable applies the enum of a CacheableResult (schema: cacheScope
// "public" | "private") and the range of its ttlMs (schema "@minimum 0")
// the way the caching page asks of a client: "If ttlMs is negative, clients
// SHOULD ignore it and treat it as 0", so a negative one is set to 0 and the
// result is accepted. An absent cacheScope is let through, as an absent
// resultType is: nothing here caches, so the field decides nothing, and
// refusing a server for omitting it would mount fewer servers for no
// protection.
func checkCacheable(method string, ttl *float64, scope string) error {
if *ttl < 0 {
*ttl = 0
}
if scope != "" && scope != "public" && scope != "private" {
return fmt.Errorf("%w: %s: cacheScope is %q, not \"public\" or \"private\"", ErrInvalidResult, method, Clean(scope, 32))
}
return nil
}
// ResultTypeOf reads a result's resultType: absent is complete (a server
// of an earlier revision), complete and input_required are known, anything
// else is invalid (basic/index#resulttype).
func ResultTypeOf(result json.RawMessage) (string, error) {
var probe struct {
ResultType *string `json:"resultType"`
}
if err := json.Unmarshal(result, &probe); err != nil {
return "", fmt.Errorf("%w: result is not an object: %v", ErrInvalidResult, err)
}
if probe.ResultType == nil {
return ResultComplete, nil
}
switch *probe.ResultType {
case ResultComplete, ResultInputRequired:
return *probe.ResultType, nil
}
return "", fmt.Errorf("%w: unknown resultType %q", ErrInvalidResult, *probe.ResultType)
}
// Discover is server/discover. A result is a modern server; an Error with
// a code this revision defines is a modern server too (the caller reads
// data.supported); any other error, or a malformed result, is ErrLegacy
// (basic/transports/stdio#backward-compatibility: "The fallback MUST NOT
// be keyed to one specific error code").
func (c *Client) Discover(ctx context.Context) (DiscoverResult, error) {
var d DiscoverResult
rt, err := c.Call(ctx, "server/discover", nil, &d)
if err != nil {
var e *Error
if errors.As(err, &e) && isModernCode(e.Code) {
return d, err
}
if errors.Is(err, ErrInvalidResult) || errors.As(err, &e) {
return d, fmt.Errorf("%w (%v)", ErrLegacy, err)
}
return d, err
}
if rt != ResultComplete || len(d.SupportedVersions) == 0 {
return d, fmt.Errorf("%w (server/discover returned no supportedVersions)", ErrLegacy)
}
if err := checkCacheable("server/discover", &d.TTLMs, d.CacheScope); err != nil {
return d, fmt.Errorf("%w (%v)", ErrLegacy, err)
}
if d.Meta != nil && d.Meta.ServerInfo != nil {
d.ServerInfo = *d.Meta.ServerInfo
}
return d, nil
}
// isModernCode is the set a 2026-07-28 server emits for a request it
// understood but refused: the three MCP codes. An unknown method or
// invalid params could come from either era, so they do not identify one.
func isModernCode(code int) bool {
return code == HeaderMismatch || code == MissingRequiredClientCapability || code == UnsupportedProtocolVersion
}
// ListTools is tools/list, following nextCursor until the list ends: a page
// with no nextCursor (absent or null) ends it, and an empty one is a cursor,
// sent back as one (pagination: a client MUST NOT treat it as the end). The
// walk is bounded because the server is not trusted to end it: at most
// MaxListPages requests, at most MaxTools tools in all, and a cursor that
// repeats one already followed is a loop. Each is ErrListLimit, naming the
// bound; Mount adds the server's name. The caller's deadline bounds the
// time (Open gives one).
func (c *Client) ListTools(ctx context.Context) ([]Tool, error) {
var all []Tool
var cursor *string // nil on the first request
followed := map[string]bool{}
for pages := 1; ; pages++ {
params := map[string]any{}
if cursor != nil {
params["cursor"] = *cursor
}
var page ListToolsResult
rt, err := c.Call(ctx, "tools/list", params, &page)
if err != nil {
return nil, err
}
if rt != ResultComplete {
return nil, fmt.Errorf("%w: tools/list answered %s", ErrInvalidResult, rt)
}
if err := checkCacheable("tools/list", &page.TTLMs, page.CacheScope); err != nil {
return nil, err
}
all = append(all, page.Tools...)
if len(all) > MaxTools {
return nil, fmt.Errorf("%w: more than %d tools (MaxTools)", ErrListLimit, MaxTools)
}
if page.NextCursor == nil {
return all, nil // absent or null; an empty string is a cursor (pagination: MUST NOT be the end)
}
if followed[*page.NextCursor] {
return nil, fmt.Errorf("%w: the server repeated a cursor (a list that loops)", ErrListLimit)
}
followed[*page.NextCursor] = true
if pages >= MaxListPages {
return nil, fmt.Errorf("%w: more than %d pages (MaxListPages)", ErrListLimit, MaxListPages)
}
cursor = page.NextCursor
}
}
// CallTool is tools/call. An input_required result is returned as is with
// ResultType set, for the caller to refuse or answer.
func (c *Client) CallTool(ctx context.Context, name string, args json.RawMessage) (CallToolResult, error) {
params := map[string]any{"name": name}
if len(args) > 0 {
params["arguments"] = args
}
var res CallToolResult
rt, err := c.Call(ctx, "tools/call", params, &res)
if err != nil {
return res, err
}
res.ResultType = rt
if rt == ResultInputRequired && (len(res.InputRequests) == 0 || string(res.InputRequests) == "null") && res.RequestState == "" {
// schema InputRequiredResult: "At least one of inputRequests or
// requestState MUST be present."
return res, fmt.Errorf("%w: an input_required result with neither inputRequests nor requestState", ErrInvalidResult)
}
return res, nil
}
// Close closes the transport.
func (c *Client) Close() error { return c.T.Close() }
// SupportedFrom reads data.supported out of an UnsupportedProtocolVersion
// error, for a message that names what the server would take.
func SupportedFrom(e *Error) []string {
if e == nil || e.Code != UnsupportedProtocolVersion {
return nil
}
var d struct {
Supported []string `json:"supported"`
}
_ = json.Unmarshal(e.Data, &d)
return d.Supported
}
// Describe is the one-line form a daemon logs for a mounted server. Every
// word in it is the server's, so each is cleaned (Clean): a name with an
// escape or a newline in it is shown as escapes, on one line.
func Describe(d DiscoverResult) string {
versions := make([]string, 0, len(d.SupportedVersions))
for _, v := range d.SupportedVersions {
versions = append(versions, Clean(v, 32))
}
return fmt.Sprintf("%s %s: versions %s", Clean(d.ServerInfo.Name, 128), Clean(d.ServerInfo.Version, 64), strings.Join(versions, ","))
}
The listing is the whole client. There is no connection state in it to lose.
The caching page speaks of ttlMs twice. Servers “MUST provide a ttlMs value that is >= 0”, and “If ttlMs is negative, clients SHOULD ignore it and treat it as 0”. checkCacheable follows the second: a negative ttlMs is set to 0 and the reply is accepted, in server/discover and in tools/list. The first version refused it, which failed the mount on a field nothing here reads, and read a server/discover reply with one as ErrLegacy, a misdiagnosis; TestCacheableFieldsAreNumbers holds the reading. The page also differs from the schema about the type: the schema types the field number (@minimum 0), the page says “an integer”, and the code accepts any JSON number, 1e3 and 60000.0 included, because a server that serialises a float is still a server of this revision.
Tools: three methods and what a tool is
A tool server answers server/discover, tools/list and tools/call. The set of tools “MUST NOT vary per-connection or as a side effect of other requests on the connection”, and servers “SHOULD return tools in a deterministic order” (server/tools), so sortedTools sorts by name whatever order the daemon registered them in. A list result is a cacheable result: it carries ttlMs and cacheScope, public for a list that is the same for every user (caching). Lists are paginated with an opaque cursor. This server never paginates, so it never sends a nextCursor and in particular never an empty one. The client follows nextCursor until it is absent, under bounds the trust section meets, and it follows the pagination page’s rule for what a cursor’s value means (Implementation Guidelines, item 3): a client must make no determination from it “other than whether a non-null value was provided (e.g. an empty string is a valid cursor and thus MUST NOT be treated as the end of results)”. ListToolsResult.NextCursor is therefore a *string: nil, an absent member or a null, ends the list, and a pointer to "" is a cursor that the next request sends back as "cursor":"". An earlier version read "" as the end, a convenience that broke the MUST, and a review found it; TestEmptyCursorIsACursor holds the fix, and the lab has a test of the same exchange.
Errors have two channels, and the model should see only one of them. A protocol error (an unknown tool, a malformed request) is a JSON-RPC error. A failure inside the tool is a successful reply with isError: true, and the specification says why the second matters: “Clients SHOULD provide tool execution errors to language models to enable self-correction.” Chapter 27’s rule that a tool’s errors are observations the model reads, not exceptions, maps onto the second channel directly, and this client maps the first onto it too: a JSON-RPC error from tools/call becomes an error: observation, because the model asked for a tool the server does not have and should learn that. input_required is the third outcome. A server may answer tools/call with a result whose resultType is input_required, carrying inputRequests (the specification’s list of what it wants: an elicitation, a sampling request, a roots list) and an opaque requestState to echo on the retry. This client answers none. The mounted call returns an error: observation saying the server needs input and that this client does not answer input requests, naming the request keys inside the fence; a result with neither inputRequests nor requestState is invalid by the schema and is refused as such.
// Tool is a server's tool definition (schema Tool). InputSchema must be a
// JSON Schema object with type "object" (server/tools#tool); it is kept
// raw because this book's checker (chapter 25) decides what it can apply.
// Description and Annotations are untrusted text (the specification's own
// Tool Safety principle): Mount passes the description to the model as the
// tool spec and reads annotations only from a Trusted server.
type Tool struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"`
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
Annotations *Annotations `json:"annotations,omitempty"`
}
// Annotations are the schema's ToolAnnotations: hints, never facts.
type Annotations struct {
Title string `json:"title,omitempty"`
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
DestructiveHint *bool `json:"destructiveHint,omitempty"`
IdempotentHint *bool `json:"idempotentHint,omitempty"`
OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}
// Content is one ContentBlock: text, image or audio (Data is base64 on the
// wire, as the schema's @format byte says), resource_link (URI, Name,
// MimeType) or resource (Resource holds the embedded contents).
type Content struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
URI string `json:"uri,omitempty"`
Name string `json:"name,omitempty"`
Resource json.RawMessage `json:"resource,omitempty"`
}
// MarshalJSON writes a text block's "text" even when it is empty: the
// schema's TextContent.text is required, and a command that prints nothing
// is an empty string, not an absent member. Every other block keeps its
// optional members out when they are empty.
func (c Content) MarshalJSON() ([]byte, error) {
type plain Content
if c.Type == "text" {
return json.Marshal(struct {
plain
Text string `json:"text"`
}{plain(c), c.Text})
}
return json.Marshal(plain(c))
}
// TextContent builds a text block.
func TextContent(s string) Content { return Content{Type: "text", Text: s} }
// CallToolResult is tools/call's result. ResultType is "complete" for an
// answer and "input_required" for a multi round-trip request (MRTR), in
// which case InputRequests and RequestState carry what the server wants;
// this client answers no input request (chapter 47 decides whether the
// principal may be asked). IsError is a tool execution error the model
// should see (server/tools#error-handling); a protocol error is a JSON-RPC
// error instead.
type CallToolResult struct {
ResultType string `json:"resultType"`
Content []Content `json:"content"`
StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
InputRequests json.RawMessage `json:"inputRequests,omitempty"`
RequestState string `json:"requestState,omitempty"`
Meta *Meta `json:"_meta,omitempty"`
}
// ListToolsResult is tools/list's result: a CacheableResult, so ttlMs and
// cacheScope are required (server/utilities/caching#cacheable-results).
// TTLMs is the schema's number, not an integer: a server that writes
// 60000.0 or 1.5e3 is a server of this revision. NextCursor is
// PaginatedResult.nextCursor, a pointer because pagination says a client
// must make no determination from a cursor's value "other than whether a
// non-null value was provided (e.g. an empty string is a valid cursor and
// thus MUST NOT be treated as the end of results)": nil (absent, or null) is
// the end of the list, and a pointer to "" is a cursor like any other.
type ListToolsResult struct {
ResultType string `json:"resultType"`
Tools []Tool `json:"tools"`
NextCursor *string `json:"nextCursor,omitempty"`
TTLMs float64 `json:"ttlMs"`
CacheScope string `json:"cacheScope"`
Meta *Meta `json:"_meta,omitempty"`
}
// DiscoverResult is server/discover's result (schema DiscoverResult at
// 4a04acd): supportedVersions, capabilities, instructions, and the
// cacheable fields. The server's identity is not a field of it: it travels
// in _meta as io.modelcontextprotocol/serverInfo, which the client copies
// into ServerInfo.
type DiscoverResult struct {
ResultType string `json:"resultType"`
SupportedVersions []string `json:"supportedVersions"`
Capabilities Capabilities `json:"capabilities"`
Instructions string `json:"instructions,omitempty"`
TTLMs float64 `json:"ttlMs"`
CacheScope string `json:"cacheScope"`
Meta *Meta `json:"_meta,omitempty"`
ServerInfo Info `json:"-"`
}
// The result types the core protocol defines. Any other value is invalid
// to this client; an absent one reads as complete (basic/index#resulttype).
const (
ResultComplete = "complete"
ResultInputRequired = "input_required"
)
A tool’s inputSchema must be a JSON Schema object, 2020-12 unless it declares a dialect, and the base protocol’s “JSON Schema Usage” requires clients and servers to validate schemas “according to their declared or default dialect”. That requirement meets chapter 25. toolcall.Decode validates the model’s arguments against the tool’s Spec().Parameters with jsonschema.Validate, which applies a fixed set: twenty-three keywords (type, properties, patternProperties, required, additionalProperties, enum, const, items, the numeric, length and item-count bounds, pattern, anyOf, oneOf, allOf, $ref, $defs, definitions) and ten annotations that constrain nothing (title, description, default, examples, $schema, $id, $comment, deprecated, readOnly, writeOnly). A server’s schema is free to use if, not, prefixItems, dependentSchemas, format, uniqueItems or the array form of items. A validator that skips what it does not know would pass a call that violates such a schema, and the loop would report the check as passed. The choices are to extend the validator (not this chapter’s work) or to exclude the tool and say why. Check excludes, and the exclusion declines a MUST of the same section: “Clients and servers MUST support JSON Schema 2020-12 for schemas without an explicit $schema field”. A schema that uses if or prefixItems is a valid schema of this revision. This client mounts only the tools whose schemas use the keywords above, and excludes the others by name, with the reason logged, because a schema it can only partly check would let through arguments that the server’s own validation was written to refuse. A tool excluded this way is a conformance gap of this client, and the chapter states it as one. Check is the whole decision of what may be mounted:
// Mount lists a server's tools and returns one agent.Tool per tool it can
// stand behind, named prefix + "__" + name. A tool is excluded, with the
// reason, when its name is outside ToolNamePattern, its inputSchema is not
// an object schema, chapter 25's checker cannot apply every keyword in it
// (so toolcall.Decode's check of the model's arguments would be a
// pretence), a $ref in it names a network URI (which this client never
// dereferences, basic/index#ref-resolution), or, over a transport that
// mirrors headers, its x-mcp-header annotations are invalid. The
// description reaches the model as the tool spec, where nothing can fence
// it, so a description over MaxDescriptionBytes, or a schema over
// MaxSchemaBytes, excludes the tool; trust decides whether every call is
// Marked. A server over MaxTools or MaxListPages, or whose list loops,
// fails the mount with an error that names it. Every name and reason in
// Excluded is the server's text, cleaned (Clean).
func Mount(ctx context.Context, c *Client, prefix string, trust Trust) ([]agent.Tool, []Excluded, error) {
if prefix == "" || strings.Contains(prefix, "__") || !ToolNamePattern.MatchString(prefix) {
return nil, nil, fmt.Errorf("mcp: a mount prefix is 1-128 characters of [A-Za-z0-9_.-] without a double underscore, not %q", prefix)
}
tools, err := c.ListTools(ctx)
if err != nil {
return nil, nil, fmt.Errorf("mcp: server %s: %w", prefix, err)
}
mirror, _ := c.T.(HeaderMirroring)
var out []agent.Tool
var excluded []Excluded
seen := map[string]bool{}
for _, t := range tools {
if reason := Check(t); reason != "" {
excluded = append(excluded, Excluded{Clean(t.Name, 128), Clean(reason, 512)})
continue
}
if seen[t.Name] {
excluded = append(excluded, Excluded{Clean(t.Name, 128), "a second tool with this name"})
continue
}
seen[t.Name] = true
if mirror != nil && mirror.MirrorsHeaders() {
params, err := HeaderParams(t.InputSchema)
if err != nil {
excluded = append(excluded, Excluded{Clean(t.Name, 128), Clean("invalid x-mcp-header: "+err.Error(), 512)})
continue
}
mirror.SetHeaderParams(t.Name, params)
}
out = append(out, &Mounted{Client: c, Tool: t, Prefix: prefix, Trust: trust})
}
return out, excluded, nil
}
// Check applies the schema conditions of Mount to one tool definition and
// returns "" when it may be mounted. It is exported so the lab and the
// conformance fixtures can test it without a transport.
func Check(t Tool) string {
if !ToolNamePattern.MatchString(t.Name) {
return "tool name is not 1-128 characters of [A-Za-z0-9_.-]"
}
if len(t.Description) > MaxDescriptionBytes {
return fmt.Sprintf("the description is %d bytes, over the limit of %d (MaxDescriptionBytes)", len(t.Description), MaxDescriptionBytes)
}
if len(t.InputSchema) > MaxSchemaBytes {
return fmt.Sprintf("inputSchema is %d bytes, over the limit of %d (MaxSchemaBytes)", len(t.InputSchema), MaxSchemaBytes)
}
if len(t.InputSchema) == 0 || string(t.InputSchema) == "null" {
return "inputSchema is null (server/tools#tool: it MUST be a valid JSON Schema object)"
}
var s map[string]any
if err := json.Unmarshal(t.InputSchema, &s); err != nil {
return "inputSchema is not an object: " + err.Error()
}
if typ, _ := s["type"].(string); typ != "object" {
return "inputSchema's type is not \"object\""
}
// basic/index#json-schema-usage: a schema without $schema is 2020-12,
// and an unsupported dialect MUST be answered with an error. This
// client's checker (chapter 25) is 2020-12 only.
if d, ok := s["$schema"]; ok {
if ds, _ := d.(string); strings.TrimSuffix(ds, "#") != "https://json-schema.org/draft/2020-12/schema" {
return "inputSchema declares a dialect other than JSON Schema 2020-12, which this client's checker does not apply"
}
}
if u := unsupported(t.InputSchema); len(u) > 0 {
return "inputSchema uses keywords this book's checker cannot apply: " + strings.Join(u, ", ")
}
if ref := networkRef(s); ref != "" {
return "inputSchema has a $ref to a network URI or another document, which is never dereferenced: " + ref
}
return ""
}
// unsupported is jsonschema.Unsupported without x-mcp-header, which is a
// transport annotation that constrains nothing (HeaderParams checks it).
func unsupported(schema json.RawMessage) []string {
var out []string
for _, k := range jsonschema.Unsupported(schema) {
if k != "x-mcp-header" {
out = append(out, k)
}
}
return out
}
// networkRef finds the first $ref that is not a fragment-only reference
// ("#/$defs/x"): a scheme, a "//host" and a relative document ("other.json")
// all name something this client would have to fetch, and never does.
func networkRef(node any) string {
switch v := node.(type) {
case map[string]any:
if ref, ok := v["$ref"].(string); ok && !strings.HasPrefix(ref, "#") {
return ref
}
for _, child := range v {
if r := networkRef(child); r != "" {
return r
}
}
case []any:
for _, child := range v {
if r := networkRef(child); r != "" {
return r
}
}
}
return ""
}
// Mounted is one mounted tool. Spec's Parameters is the server's
// inputSchema, so the loop's toolcall.Decode validates the model's
// arguments against it before Call runs (chapter 44).
type Mounted struct {
Client *Client
Tool Tool
Prefix string
Trust Trust
CallTimeout time.Duration // default 60 s; Timeout() reports it to the loop
}
func (m *Mounted) Name() string { return m.Prefix + "__" + m.Tool.Name }
// Spec is the tool as the model sees it. Mount excludes a description over
// MaxDescriptionBytes; a Mounted built another way is cut to it here, and
// control characters in it are escaped, because nothing downstream will.
func (m *Mounted) Spec() llm.Tool {
desc, _ := cutBytes(m.Tool.Description, MaxDescriptionBytes)
return llm.Tool{Name: m.Name(), Description: sanitize(desc), Parameters: m.Tool.InputSchema}
}
// NeedsApproval: every call to an Untrusted server's tool is Marked.
func (m *Mounted) NeedsApproval(call toolcall.Call) (bool, string) {
if m.Trust == Trusted {
return false, ""
}
return true, "mcp server " + m.Prefix + " is untrusted: " + m.Tool.Name + " needs approval"
}
// Idempotent is chapter 26's flag: a repeated call in a run may be answered
// from the first, and the call does not advance the write generation (the
// loop treats it as a read). It is true only for a Trusted server's tool
// whose readOnlyHint is true (ruling 7e-E3). idempotentHint decides
// nothing: the schema defines it as "meaningful only when readOnlyHint ==
// false", so it describes a write that is safe to repeat, and treating a
// write as a cacheable read gives a stale read and a write that never runs.
// An Untrusted server's annotations decide nothing (schema ToolAnnotations:
// "Clients should never make tool use decisions based on ToolAnnotations
// received from untrusted servers"). That chapter 40's resume replays an
// in-flight call of such a tool is what Idempotent means for the daemon's
// own read tools, and is intended.
func (m *Mounted) Idempotent() bool {
if m.Trust != Trusted || m.Tool.Annotations == nil {
return false
}
h := m.Tool.Annotations.ReadOnlyHint
return h != nil && *h
}
// Timeout is the loop's deadline for a call (agent.Timeouter): 60 s unless
// CallTimeout is set. Without it the loop's own 30 s default would cut a
// mounted call before this tool's.
func (m *Mounted) Timeout() time.Duration { return m.TimeoutDuration() }
func (m *Mounted) TimeoutDuration() time.Duration {
if m.CallTimeout == 0 {
return 60 * time.Second
}
return m.CallTimeout
}
// Call sends tools/call and maps the result to an observation: text
// blocks become text parts, images image_url data URLs (only the four
// formats and sizes ContentParts checks), audio and resources are named in
// text (no fleet model takes audio; a resource's text is quoted under its
// URI), isError becomes an error observation, and an input_required result
// is an error observation naming what the server asked for, since this
// client answers no input request. Every string the server controls that
// reaches the model, a result's text, a JSON-RPC error's message, a
// transport error and an input request's keys, goes through the same fence,
// prompt.Quote under this tool's name, cleaned of control characters and
// cut to a bound first.
func (m *Mounted) Call(ctx context.Context, call toolcall.Call) agent.Result {
ctx, cancel := context.WithTimeout(ctx, m.TimeoutDuration())
defer cancel()
args, err := json.Marshal(call.Arguments)
if err != nil {
return agent.ErrorResult("%s: arguments: %v", m.Name(), err)
}
res, err := m.Client.CallTool(ctx, m.Tool.Name, args)
if err != nil {
var e *Error
if errors.As(err, &e) {
return agent.ErrorResult("%s: the server refused the call, code %d, saying:\n%s", m.Name(), e.Code, m.fenceError(e.Message))
}
return agent.ErrorResult("%s: the call failed:\n%s", m.Name(), m.fenceError(err.Error()))
}
if res.ResultType == ResultInputRequired {
keys := inputRequestKeys(res.InputRequests)
return agent.ErrorResult("%s: the server needs input before it can answer, and this client does not answer input requests; its request keys:\n%s", m.Name(), m.fenceError(keys))
}
parts := ContentParts(m.Name(), res.Content)
if len(res.Content) == 0 && len(res.StructuredContent) > 0 && string(res.StructuredContent) != "null" {
// A result may carry only structuredContent (the schema's content
// is required, but a server of this revision may leave it empty):
// show the model the JSON, fenced and bounded like any text.
parts = ContentParts(m.Name(), []Content{TextContent(string(res.StructuredContent))})
}
if res.IsError {
text := ""
for _, p := range parts {
if p.Type == "text" {
text += p.Text
}
}
return agent.ErrorResult("%s: %s", m.Name(), strings.TrimSpace(text))
}
if len(parts) == 0 {
return agent.EmptyResult(m.Name())
}
return agent.Result{Kind: agent.KindOK, Parts: parts}
}
// fenceError is a piece of server text in an error observation: cut to
// MaxErrorTextBytes, control characters escaped, quoted under the tool's
// name. The cut is stated outside the fence.
func (m *Mounted) fenceError(text string) string {
kept, dropped := cutBytes(text, MaxErrorTextBytes)
out := prompt.Quote(m.Name(), sanitize(kept))
if dropped > 0 {
out += fmt.Sprintf("\n[the server's text was cut: %d more bytes]", dropped)
}
return out
}
// ContentParts maps content blocks to llm.Parts. Text is quoted under the
// tool's name with prompt.Quote, because a tool result is data, not
// instructions (chapter 27), after control characters are escaped. The text
// parts together, as the model receives them (the fences, the labels, the
// newlines, the escapes and the cut marker included), are at most
// MaxObservationBytes: the cut is made after escaping, the fence's own bytes
// are charged to the budget, a resource's URI label is cut to 256 bytes, at
// most MaxResultBlocks blocks are read, and a line outside the fence, at most
// ObservationMarkerBytes long, says how much was left out. When nothing is
// cut the whole budget is the text's. An image becomes a data: URL only when
// its type is image/png, image/jpeg, image/gif or image/webp, its data is
// base64 that decodes to MaxImageBytes or fewer bytes starting with that
// format's signature; any other image is named in text, as audio is. The URL
// rides in the tool message and is bounded by that rule, not by the text
// budget; chapter 28's router reads images from the last user message only
// (agent.routeRequest), so a tool-result image is not routed to a vision
// model, it goes to whichever model serves the turn. A resource_link is
// named; an embedded text resource is quoted under its URI; audio and blob
// resources are named and not carried.
func ContentParts(name string, blocks []Content) []llm.Part {
if parts, cut := contentParts(name, blocks, MaxObservationBytes); !cut {
return parts
}
parts, _ := contentParts(name, blocks, MaxObservationBytes-ObservationMarkerBytes)
return parts
}
// seg is one piece of a run of text: a line, or a resource with its own fence.
type seg struct {
label string // a resource's label; "" for a line
body string // escaped
}
// contentParts renders blocks with at most budget bytes of text, and reports
// whether anything was left out; when it was, the marker line is appended
// (the caller has left room for it).
func contentParts(name string, blocks []Content, budget int) (parts []llm.Part, cut bool) {
moreBlocks := 0
if len(blocks) > MaxResultBlocks {
moreBlocks, blocks = len(blocks)-MaxResultBlocks, blocks[:MaxResultBlocks]
}
left, dropped := budget, 0
var run []seg
flush := func() {
if len(run) == 0 {
return
}
out, kept, total := renderRun(name, run, left)
left -= len(out)
dropped += total - kept
if out != "" {
parts = append(parts, llm.Part{Type: "text", Text: out})
}
run = nil
}
line := func(s string) { run = append(run, seg{body: sanitize(s)}) }
for _, b := range blocks {
switch b.Type {
case "text":
line(b.Text)
case "image":
url, note := imageURL(b)
if note != "" {
line(note)
break
}
flush()
parts = append(parts, llm.Part{Type: "image_url", URL: url})
case "audio":
line("(an audio block of type " + Clean(b.MimeType, 64) + " was returned and not carried)")
case "resource_link":
line("(resource " + Clean(b.URI, 256) + ")")
case "resource":
var rc struct {
URI string `json:"uri"`
MimeType string `json:"mimeType"`
Text *string `json:"text"`
Blob *string `json:"blob"`
}
_ = json.Unmarshal(b.Resource, &rc)
// The label is cleaned (which can expand an escape to four bytes)
// and cut again, because prompt.Quote writes it twice.
label, _ := cutBytes(Clean(rc.URI, 256), 256)
if rc.Text != nil {
run = append(run, seg{label: label, body: sanitize(*rc.Text)})
} else {
line("(resource " + label + " of type " + Clean(rc.MimeType, 64) + " is binary and was not carried)")
}
default:
line("(a content block of unknown type " + Clean(b.Type, 64) + " was returned and not carried)")
}
}
flush()
if dropped > 0 || moreBlocks > 0 {
parts = append(parts, llm.Part{Type: "text", Text: fmt.Sprintf("[the server's result was cut: %d more bytes and %d more blocks than the %d (MaxObservationBytes) bytes and %d (MaxResultBlocks) blocks kept]", dropped, moreBlocks, MaxObservationBytes, MaxResultBlocks)})
return parts, true
}
return parts, false
}
// renderRun fences a run of segments under name in at most left bytes. It
// keeps as many of the segments' body bytes as fit with every fence charged
// (a fence widens with the text it must not be closed by, so the fit is found
// by cutting the excess and rendering again), and returns the text, the body
// bytes kept and the body bytes there were. A run with nothing kept, but
// something to keep, renders as "".
func renderRun(name string, run []seg, left int) (out string, kept, total int) {
for _, s := range run {
total += len(s.body)
}
if left <= 0 {
return "", 0, total
}
render := func(allow int) (string, int) {
var b strings.Builder
used := 0
for _, s := range run {
body, _ := cutBytes(s.body, allow-used)
used += len(body)
if s.label != "" {
b.WriteString(prompt.Quote(s.label, body))
} else {
b.WriteString(body)
}
b.WriteString("\n")
}
return prompt.Quote(name, strings.TrimRight(b.String(), "\n")), used
}
allow := min(total, left)
for i := 0; i < 64; i++ {
text, used := render(allow)
if len(text) <= left {
if used == 0 && total > 0 {
return "", 0, total
}
return text, used, total
}
allow = max(allow-(len(text)-left), 0)
}
return "", 0, total
}
// imageSignatures are the formats carried and the bytes each starts with.
var imageSignatures = map[string][][]byte{
"image/png": {[]byte("\x89PNG\r\n\x1a\n")},
"image/jpeg": {[]byte("\xff\xd8\xff")},
"image/gif": {[]byte("GIF87a"), []byte("GIF89a")},
"image/webp": {[]byte("RIFF")}, // and "WEBP" at byte 8, below
}
// imageURL returns the data: URL for an image block, or, when the block is
// not one this client carries, a one-line note saying why. The URL is built
// from the decoded bytes (re-encoded), never from the server's string.
func imageURL(b Content) (url, note string) {
mime := strings.ToLower(strings.TrimSpace(b.MimeType))
sigs, ok := imageSignatures[mime]
if !ok {
return "", "(an image block of type " + Clean(b.MimeType, 64) + " was returned and not carried: only image/png, image/jpeg, image/gif and image/webp are)"
}
if base64.StdEncoding.DecodedLen(len(b.Data)) > MaxImageBytes+3 {
return "", fmt.Sprintf("(an image block of type %s was returned and not carried: more than %d bytes, MaxImageBytes)", mime, MaxImageBytes)
}
// Strict decoding and the check of the error are not what keeps a bad
// image out: the data: URL below is built from the decoded bytes, never
// from the server's string, and the bytes must begin with the format's
// signature. A lax decoder, or one whose error was ignored, would give the
// same URL for the same bytes or a signature that fails.
raw, err := base64.StdEncoding.Strict().DecodeString(b.Data)
if err != nil || len(raw) == 0 {
return "", "(an image block of type " + mime + " was returned and not carried: its data is not base64)"
}
if len(raw) > MaxImageBytes {
return "", fmt.Sprintf("(an image block of type %s was returned and not carried: %d bytes, over MaxImageBytes %d)", mime, len(raw), MaxImageBytes)
}
match := false
for _, sig := range sigs {
if bytes.HasPrefix(raw, sig) {
match = true
}
}
if mime == "image/webp" && !(match && len(raw) >= 12 && string(raw[8:12]) == "WEBP") {
match = false
}
if !match {
return "", "(an image block of type " + mime + " was returned and not carried: its bytes are not that format)"
}
return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(raw), ""
}
// inputRequestKeys names the keys of an input_required result, sorted and
// at most 16, for a message that will be fenced.
func inputRequestKeys(raw json.RawMessage) string {
var m map[string]json.RawMessage
if err := json.Unmarshal(raw, &m); err != nil || len(m) == 0 {
return "no input requests, request state only"
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
more := 0
if len(keys) > 16 {
more, keys = len(keys)-16, keys[:16]
}
out := strings.Join(keys, ", ")
if more > 0 {
out += fmt.Sprintf(" and %d more", more)
}
return out
}
Mount lists the tools, runs Check on each, and returns one agent.Tool per tool it can stand behind, named prefix__name, with an Excluded entry (name and reason) for each it cannot. A tool is excluded for a name outside [A-Za-z0-9_.-]{1,128} (a SHOULD in the specification, a condition here, because the name becomes part of an agent.Tool name that reaches the model, and the double underscore is the prefix separator); a null or non-object inputSchema; a $schema other than 2020-12; a keyword outside the set, reported by name; a $ref that is not fragment-only, since this client never fetches anything; a description over 8 KiB or a schema over 32 KiB; and, over a transport that mirrors headers, an invalid x-mcp-header.
Mounted.Call, in the listing, is the subject of the trust section further on. The transports come first, because they decide what a message is on the wire.
stdio: one line, one message, one id
stdio’s framing is the whole of its specification: messages “are delimited by newlines, and MUST NOT contain embedded newlines”, UTF-8, and the server “MUST NOT write anything to its stdout that is not a valid MCP message”. The reader is bounded. A line may be 16 MiB including its newline (MaxLine); a line of exactly that length is read, and one byte more is a FramingError with Fatal set, answered -32700 without an id and followed by the stream closing, because the rest of the line is still unread and cannot be told from the next message. Every other framing error leaves the stream usable: a message split across two lines is two parse errors and never one message, since the first half is not JSON.
// MaxLine bounds one message. A line longer than this fails the read,
// because an unbounded line is a memory exhaustion from a peer. The count
// includes the newline: a 16 MiB line with its newline is read, one byte
// more is fatal.
const MaxLine = 16 << 20
// WriteTimeout bounds one write to a peer that has stopped reading: 30 s is
// far longer than a pipe or socket takes to drain a 16 MiB line from a
// peer that is reading, and short enough that a stuck peer costs one
// request's time, not the daemon's. A write that is not done by then, or
// whose context ends first, fails the connection (a half-written line
// cannot be resynchronised).
const WriteTimeout = 30 * time.Second
// writeTimeout is WriteTimeout, read when a stream is set up; a test shortens
// it (export_test.go) to reach the timeout without waiting for it.
var writeTimeout = WriteTimeout
// EOFGrace is how long Serve lets requests in flight finish after its input
// ends before it cancels them: a client that writes a request and closes
// its end (a shell pipeline) still gets the answer of a request that takes
// moments, and a server is still gone "promptly" (stdio: servers SHOULD
// exit when their standard input is closed).
const EOFGrace = time.Second
// FramingError is a line that is not one UTF-8 JSON-RPC message; a server
// answers it with its ErrorCode and no id (the reply to a message whose id
// could not be read omits "id"), a client drops the connection. Code is 0
// for JSON that does not parse or is not UTF-8 (ParseError) and
// mcp.InvalidRequest for JSON that parses but is not a message (a batch, a
// bad id, a member of the wrong type). Fatal marks the one error after
// which the stream cannot be resynchronised (a line longer than MaxLine,
// whose rest is still unread): a server closes the stream instead of
// answering.
type FramingError struct {
Reason string
Fatal bool
Code int
}
func (e *FramingError) Error() string { return "mcp/stdio: " + e.Reason }
// ErrorCode is the JSON-RPC code a server answers this error with.
func (e *FramingError) ErrorCode() int {
if e.Code == 0 {
return mcp.ParseError
}
return e.Code
}
// ReadMessage reads one line and decodes it. Reading stops at '\n'; a
// final line without one is accepted at EOF; an empty line is skipped
// (nothing is on the wire); invalid UTF-8 or invalid JSON is a
// FramingError, and so is JSON that is not one message (mcp.DecodeMessage:
// a batch, a repeated member name, data after the message). A carriage
// return before the newline is JSON white space and is accepted. Messages
// never contain a raw newline, so a message a peer split across lines
// decodes as two framing errors, never as one message.
func ReadMessage(r *bufio.Reader) (mcp.Message, error) {
for {
line, err := readLine(r, MaxLine)
if err != nil {
return mcp.Message{}, err
}
line = bytes.TrimRight(line, "\r\n")
if len(bytes.TrimSpace(line)) == 0 {
continue
}
if !utf8.Valid(line) {
return mcp.Message{}, &FramingError{Reason: "the line is not valid UTF-8"}
}
m, err := mcp.DecodeMessage(line)
if err != nil {
var se *mcp.ShapeError
if errors.As(err, &se) {
return mcp.Message{}, &FramingError{Reason: se.Reason, Code: mcp.InvalidRequest}
}
return mcp.Message{}, &FramingError{Reason: "the line is not a JSON-RPC message: " + mcp.Clean(err.Error(), 200)}
}
return m, nil
}
}
// readLine reads up to and including '\n' or to EOF, at most max bytes.
func readLine(r *bufio.Reader, max int) ([]byte, error) {
var out []byte
for {
chunk, err := r.ReadSlice('\n')
out = append(out, chunk...)
if len(out) > max {
return nil, &FramingError{Reason: fmt.Sprintf("a line longer than %d bytes", max), Fatal: true}
}
if err == nil {
return out, nil
}
if err == bufio.ErrBufferFull {
continue
}
if err == io.EOF && len(out) > 0 {
return out, nil
}
return nil, err
}
}
// WriteMessage writes one message as one line. encoding/json escapes every
// newline inside strings, so the encoding never holds a raw one; the
// check is a guard on that fact.
func WriteMessage(w io.Writer, m mcp.Message) error {
b, err := encodeLine(m)
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
func encodeLine(m mcp.Message) ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
if bytes.IndexByte(b, '\n') >= 0 {
return nil, &FramingError{Reason: "the encoded message holds a newline"}
}
return append(b, '\n'), nil
}
Serve is the server side. It reads one message at a time and runs each request in its own goroutine, up to MaxInFlight (64, the server’s rate limit: the Security Considerations of server/tools list “Rate limit tool invocations” among what servers MUST do, and this server does it by refusing the 65th with InternalError, not by queueing it; it is a bound on requests in flight, not a rate). The replies come back in the order the tools finish, not the order the requests arrived. The capture’s seven lines show it: the replies carry ids 4, 3, 1, none, none, 5 and 2, in that order, and a client that matched replies to requests by position would be wrong. It matches by id, and ID.Key keeps "7" and 7 apart so that a string and a number never answer for each other.
The id discipline has a race the specification names. A request’s id must not match one “not yet received a response for”, and that is a property of one connection, so the in-flight set lives in Serve and not in Handle: a second request whose id is still open is InvalidRequest. Cancellation (notifications/cancelled) frees the id at once and cancels the request’s context; the cancelled goroutine, when its tool returns, finds that the entry in the in-flight set is no longer its own and writes nothing. The specification covers the race this closes: “cancellation notifications may arrive after request processing has completed, and potentially after a response has already been sent. Both parties MUST handle these race conditions gracefully”. TestServeDuplicateOpenID runs the sequence: a second request under an id still in flight is InvalidRequest; a cancellation releases the blocked tool and writes no reply for it; the next request under the same id is answered, and the first reply seen under that id is its own.
// Serve answers requests from r on w until r ends, a write fails, or ctx is
// cancelled. Logs go to log, never to w (the server MUST NOT write
// anything but messages to its stdout). Requests run concurrently (at most
// mcp.MaxInFlight; one more is refused, not queued), writes are serialised
// and bounded (WriteTimeout), a notifications/cancelled cancels the context
// of the request it names, and a second request with an id still in flight
// is InvalidRequest (basic/index#requests; the refusal carries that same id,
// so a client that demultiplexes by id hands it to the first caller, which
// is the client's own bug to avoid). A client sends no responses; one that
// does is answered InvalidRequest. A framing error is answered with its
// code and no id; the stream goes on, except after a line too long to
// resynchronise.
//
// Serve returns at once when ctx ends, whether or not r does: it reads r in
// a goroutine that ends when r does. When r ends it gives requests in flight
// EOFGrace to finish and then cancels them; it never waits on a handler
// whose context it has not cancelled.
func Serve(ctx context.Context, r io.Reader, w io.Writer, log io.Writer, s *mcp.Server) error {
return serve(ctx, r, w, log, s, nil, 0)
}
// deadliner is the part of a net.Conn the idle rule needs.
type deadliner interface{ SetReadDeadline(time.Time) error }
// idleNow is the clock the idle deadline is set from; a test injects one.
var idleNow = time.Now
// isTimeout reports a read that ended at its deadline.
func isTimeout(err error) bool {
var ne net.Error
return errors.As(err, &ne) && ne.Timeout()
}
// serve is Serve with the idle rule (chapter 48): when dl is set and idle
// is positive, a read deadline of idle from now is armed whenever no
// request is in flight and cleared while one is, so a connection that sends
// nothing for idle with nothing pending is closed (serve returns nil) and a
// request that takes longer than idle is not cut. The reader goroutine never
// decides: on a timeout it reports and waits, and this loop, which knows
// what it has registered, closes or clears the deadline and lets it go on.
func serve(ctx context.Context, r io.Reader, w io.Writer, log io.Writer, s *mcp.Server, dl deadliner, idle time.Duration) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
logf := func(format string, args ...any) {
if log != nil {
fmt.Fprintf(log, format, args...)
}
}
fw := newFramedWriter(w, func(err error) {
logf("%v\n", err)
cancel()
})
write := func(m mcp.Message) {
line, err := encodeLine(m)
if err != nil {
logf("mcp/stdio: write: %v\n", err)
return
}
_ = fw.write(ctx, line)
}
var wg sync.WaitGroup
type entry struct{ cancel context.CancelFunc }
inflight := map[string]*entry{}
var imu sync.Mutex
finish := func(grace time.Duration) {
if grace > 0 {
idle := make(chan struct{})
go func() { wg.Wait(); close(idle) }()
timer := time.NewTimer(grace)
select {
case <-idle:
case <-timer.C:
}
timer.Stop()
}
cancel()
wg.Wait()
}
// arm sets the idle deadline when nothing is in flight and clears it
// while something is; a no-op without the idle rule.
arm := func() {
if dl == nil || idle <= 0 {
return
}
// One critical section: the count read and the deadline set must not be
// separated, or a clear that was decided before a request finished
// can land after the deadline that request's end set.
imu.Lock()
defer imu.Unlock()
if len(inflight) == 0 {
_ = dl.SetReadDeadline(idleNow().Add(idle))
} else {
_ = dl.SetReadDeadline(time.Time{})
}
}
arm()
type read struct {
m mcp.Message
err error
}
reads := make(chan read)
resume := make(chan struct{})
go func() {
br := bufio.NewReaderSize(r, 64<<10)
for {
m, err := ReadMessage(br)
select {
case reads <- read{m, err}:
case <-ctx.Done():
return
}
if err != nil && dl != nil && isTimeout(err) {
// The loop below decides whether this was idleness; wait for
// it to clear the deadline (or to end) before reading again.
select {
case <-resume:
continue
case <-ctx.Done():
return
}
}
var fe *FramingError
if err != nil && (!errors.As(err, &fe) || fe.Fatal) {
return
}
}
}()
for {
var rd read
select {
case rd = <-reads:
case <-ctx.Done():
finish(0)
return fw.failure()
}
m, err := rd.m, rd.err
if err != nil && dl != nil && isTimeout(err) {
imu.Lock()
n := len(inflight)
imu.Unlock()
if n == 0 {
finish(0)
return nil // idle: the connection is closed by the caller
}
_ = dl.SetReadDeadline(time.Time{})
select {
case resume <- struct{}{}:
case <-ctx.Done():
}
continue
}
if err != nil {
var fe *FramingError
if errors.As(err, &fe) {
logf("%v\n", err)
write(mcp.Message{JSONRPC: mcp.JSONRPCVersion, Error: &mcp.Error{Code: fe.ErrorCode(), Message: fe.Reason}})
if fe.Fatal {
finish(0)
return err // too long: the stream cannot be resynchronised
}
continue
}
if err == io.EOF {
finish(EOFGrace)
return nil
}
finish(0)
if ctx.Err() != nil {
return fw.failure()
}
return err
}
switch m.Classify() {
case mcp.KindNotification:
if m.Method == "notifications/cancelled" {
var p struct {
RequestID mcp.ID `json:"requestId"`
}
if json.Unmarshal(m.Params, &p) == nil && p.RequestID.Set && !p.RequestID.IsNull {
imu.Lock()
if e, ok := inflight[p.RequestID.Key()]; ok {
e.cancel()
delete(inflight, p.RequestID.Key()) // the id is free at once
}
imu.Unlock()
}
}
continue
case mcp.KindRequest:
key := m.ID.Key()
imu.Lock()
if _, open := inflight[key]; open {
imu.Unlock()
write(mcp.Message{JSONRPC: mcp.JSONRPCVersion, ID: m.ID, Error: &mcp.Error{Code: mcp.InvalidRequest, Message: "id " + m.ID.String() + " is already in flight"}})
continue
}
if len(inflight) >= mcp.MaxInFlight {
imu.Unlock()
write(mcp.Message{JSONRPC: mcp.JSONRPCVersion, ID: m.ID, Error: &mcp.Error{Code: mcp.InternalError, Message: fmt.Sprintf("too many requests in flight (the limit is %d)", mcp.MaxInFlight)}})
continue
}
rctx, rcancel := context.WithCancel(ctx)
e := &entry{cancel: rcancel}
inflight[key] = e
imu.Unlock()
arm() // in flight: no idle deadline until it is answered
wg.Add(1)
go func(m mcp.Message) {
defer wg.Done()
defer func() {
imu.Lock()
if inflight[key] == e {
delete(inflight, key)
}
imu.Unlock()
rcancel()
arm() // the last answer re-arms the idle deadline
}()
reply := s.Handle(rctx, m)
if rctx.Err() != nil && ctx.Err() == nil {
return // cancelled: no response (basic/patterns/cancellation)
}
if reply.JSONRPC != "" {
write(reply)
}
}(m)
default:
write(s.Handle(ctx, m))
}
}
}
// ServeListener accepts connections and serves each with Serve; check, if
// set, is called with each connection before a byte is read (the daemon's
// SO_PEERCRED rule) and a non-nil error closes it. When ctx ends the
// listener is closed, every accepted connection is closed (Serve returns
// and its connection is closed with it), and ServeListener returns once
// they have; a connection whose client hangs up is closed at its own end.
// It is ServeListenerIdle with no idle deadline.
func ServeListener(ctx context.Context, l net.Listener, s *mcp.Server, log io.Writer, check func(net.Conn) error) error {
return ServeListenerIdle(ctx, l, s, log, check, 0)
}
// ServeListenerIdle is ServeListener with an idle deadline per connection
// (0: none, today's behaviour): a connection that sends nothing for idle
// while no request is in flight is closed (chapter 48: a client that
// connected and went away, or never spoke, cannot hold a connection open for
// the daemon's life); the listener keeps accepting.
func ServeListenerIdle(ctx context.Context, l net.Listener, s *mcp.Server, log io.Writer, check func(net.Conn) error, idle time.Duration) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
defer wg.Wait()
stop := make(chan struct{})
defer close(stop)
go func() {
select {
case <-ctx.Done():
l.Close()
case <-stop:
}
}()
for {
c, err := l.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
if check != nil {
if err := check(c); err != nil {
if log != nil {
fmt.Fprintf(log, "mcp/stdio: refused a connection: %v\n", err)
}
c.Close()
continue
}
}
wg.Add(1)
go func() {
defer wg.Done()
defer c.Close()
_ = serve(ctx, c, c, log, s, c, idle)
}()
}
}
The client’s side of the same stream is conn: a reader goroutine that demultiplexes replies into a map keyed by ID.Key, a shared writer, and Call, which registers the id, writes the line, and waits for the reply or the context. A reply for an id nobody is waiting on is dropped, and so is any message that is not a result or an error; a stream that breaks fails every call in flight with the first error. When a call’s context ends, Call sends notifications/cancelled and returns; it does not wait for the server to confirm.
// conn is the client side of one framed byte stream: a writer the callers
// share (bounded, see framedWriter), a reader goroutine that demultiplexes
// responses by id. A connection that fails, by a broken read, a framing
// error from the server or a write that did not finish, fails every call
// in flight and every later one with the first error.
type conn struct {
fw *framedWriter
mu sync.Mutex
waiting map[string]chan mcp.Message
done chan struct{}
err error
log io.Writer
}
func newConn(r io.Reader, w io.Writer, log io.Writer) *conn {
c := &conn{waiting: map[string]chan mcp.Message{}, done: make(chan struct{}), log: log}
c.fw = newFramedWriter(w, c.fail)
go c.read(bufio.NewReaderSize(r, 64<<10))
return c
}
func (c *conn) read(br *bufio.Reader) {
defer close(c.done)
for {
m, err := ReadMessage(br)
if err != nil {
var fe *FramingError
if errors.As(err, &fe) {
// A peer that writes what is not a message has broken the
// stream (the server MUST NOT): the connection is dropped.
c.fail(err)
return
}
if err == io.EOF {
c.fail(io.ErrUnexpectedEOF)
} else {
c.fail(withoutAddress(err))
}
return
}
switch m.Classify() {
case mcp.KindResult, mcp.KindError:
if m.ID == nil || !m.ID.Set || m.ID.IsNull {
// The reply to a message the server could not read (the
// schema: no id; JSON-RPC: null). It names no caller; the
// message is the server's text, cleaned by Error().
if c.log != nil {
fmt.Fprintf(c.log, "mcp/stdio: an error with no id: %v\n", m.Error)
}
continue
}
c.mu.Lock()
ch, ok := c.waiting[m.ID.Key()]
delete(c.waiting, m.ID.Key())
c.mu.Unlock()
if ok {
ch <- m
}
case mcp.KindNotification:
// Request-scoped notifications (progress, log) are dropped by
// this client; a server never sends requests (patterns).
default:
if c.log != nil {
fmt.Fprintf(c.log, "mcp/stdio: dropped a %s from the server\n", m.Classify())
}
}
}
}
func (c *conn) fail(err error) {
c.mu.Lock()
if c.err == nil {
c.err = err
}
for k, ch := range c.waiting {
close(ch)
delete(c.waiting, k)
}
c.mu.Unlock()
}
// withoutAddress drops the socket addresses a net error carries ("read unix
// @->/run/user/1000/aecd/mcp.sock: use of closed network connection"): the
// error reaches a model, and the daemon's layout is not its business.
func withoutAddress(err error) error {
var oe *net.OpError
if errors.As(err, &oe) && oe.Err != nil {
return fmt.Errorf("the connection ended: %v", oe.Err)
}
return err
}
// cancelWriteTimeout bounds the cancellation notification, which is sent
// after its request's context has ended: a stuck peer must not hold the
// caller that already gave up.
var cancelWriteTimeout = time.Second
func (c *conn) Call(ctx context.Context, req mcp.Message) (mcp.Message, error) {
if req.Classify() != mcp.KindRequest {
return mcp.Message{}, errors.New("mcp/stdio: Call takes a request")
}
line, err := encodeLine(req)
if err != nil {
return mcp.Message{}, err
}
ch := make(chan mcp.Message, 1)
c.mu.Lock()
if c.err != nil {
c.mu.Unlock()
return mcp.Message{}, c.err
}
key := req.ID.Key()
if _, open := c.waiting[key]; open {
c.mu.Unlock()
return mcp.Message{}, errors.New("mcp/stdio: id " + req.ID.String() + " is already in flight")
}
c.waiting[key] = ch
c.mu.Unlock()
if err := c.fw.write(ctx, line); err != nil {
c.mu.Lock()
delete(c.waiting, key)
c.mu.Unlock()
return mcp.Message{}, err
}
select {
case m, ok := <-ch:
if !ok {
c.mu.Lock()
err := c.err
c.mu.Unlock()
return mcp.Message{}, err
}
return m, nil
case <-ctx.Done():
c.mu.Lock()
delete(c.waiting, key)
c.mu.Unlock()
// The stdio cancellation rule: tell the server, then stop waiting.
params, _ := json.Marshal(map[string]any{"requestId": req.ID, "reason": ctx.Err().Error()})
if cl, err := encodeLine(mcp.Message{JSONRPC: mcp.JSONRPCVersion, Method: "notifications/cancelled", Params: params}); err == nil {
wctx, wcancel := context.WithTimeout(context.Background(), cancelWriteTimeout)
_ = c.fw.write(wctx, cl)
wcancel()
}
return mcp.Message{}, ctx.Err()
}
}
func (c *conn) Notify(ctx context.Context, n mcp.Message) error {
if n.Classify() != mcp.KindNotification {
return errors.New("mcp/stdio: Notify takes a notification")
}
line, err := encodeLine(n)
if err != nil {
return err
}
return c.fw.write(ctx, line)
}
The writer is the part of conn that took two rounds to get right. A write to a peer that never reads blocks in the kernel for ever, and neither a context nor a deadline reaches an io.Writer. So each write runs in its own goroutine, the caller selects on the write, its context and WriteTimeout (30 s), and when the context or the timer wins the stream is dead, because a line may be half written and the peer cannot resynchronise. That policy was right for a stuck peer and wrong for a context that had already ended. A call made under a context that was cancelled before the call began found both the semaphore and ctx.Done() ready, and Go’s select chooses at random among ready cases. When it took the semaphore, the second select found ctx.Done() ready before the write goroutine had run, declared the stream dead and closed a connection to a healthy server. The daemon then told the principal that the server had stopped, and nothing restarts a server. The agent loop can reach it: it dispatches the rest of a batch after one gate has denied or been cancelled, under a context that has ended. The loop is chapter 26’s and is unchanged (carried, below); the transport is fixed, so that a context already done returns its error before anything is taken or written, and a context that ends during a write waits cancelWriteTimeout (one second) for the line to finish, since a whole line written is not a broken stream. TestCallsWithAnEndedContextLeaveTheConnection makes 200 ended-context calls on each of 50 fresh connections and then one good call on each.
A line that has not finished within that second is a peer that has stopped reading, and that fails the stream, with an error that names the peer and does not wrap the context’s. The first fix did wrap it, and the daemon’s watched transport (the mounting section) reads an error that wraps a context’s as its caller’s own context ending, so a server that had stopped reading was never reported down: every later call failed at once, the daemon never warned, and aecd status showed the mount up. TestStuckCommandServerIsReportedDown runs the test binary as a child that never reads its input and gives it a line larger than the pipe, under a context that ends by a deadline and by a cancel: the call that gave up returns its context’s error, and the next call finds the mount down.
A subprocess is a stdio.Command. Start refuses a Cmd with a nil Env, because os/exec reads nil as “inherit everything”; it puts the child in its own process group (Setpgid); and it sets WaitDelay so that a descendant outside the group that still holds the child’s stderr cannot hold Close open. Close follows the order of the specification’s shutdown without the SIGTERM the page calls typical: close stdin, wait Grace for the exit, then SIGKILL. The kill goes to the group, not to the child, because a server that is a shell script leaves children behind, and a grandchild holding our end of stdout would keep the client’s reader alive after the server was dead. A server that had to be killed is not an error of the transport, since forced termination is the page’s own last step; Killed() reports it and the daemon logs it.
// Command runs a server as a subprocess: its stdin and stdout are the
// stream, its stderr goes to Stderr (a log, never parsed). Close follows
// the specification's shutdown order: close stdin, wait Grace for the
// exit, then kill by handle and wait.
type Command struct {
Cmd *exec.Cmd
Stderr io.Writer
Grace time.Duration // default 2 s
stdin io.WriteCloser
conn *conn
once sync.Once
wait chan error
killed bool
}
// Start starts the process. The caller builds Cmd (argv, Dir, Env) and the
// environment is exactly Cmd.Env: a nil Env is refused, because os/exec
// reads it as "inherit everything the daemon has", the keys among it, and a
// server gets only what it is given (an empty, non-nil slice is no
// variables at all). Cmd.WaitDelay defaults to one second, so a server
// that exits while a descendant outside its process group still holds its
// stderr cannot keep Close waiting for that descendant for ever.
func (c *Command) Start(ctx context.Context) error {
if c.Cmd == nil {
return errors.New("mcp/stdio: no command")
}
if c.Cmd.Env == nil {
return errors.New("mcp/stdio: Cmd.Env is nil, which would give the server the whole environment of this process; set it (a non-nil empty slice for none)")
}
stdin, err := c.Cmd.StdinPipe()
if err != nil {
return err
}
stdout, err := c.Cmd.StdoutPipe()
if err != nil {
return err
}
if c.Stderr != nil {
c.Cmd.Stderr = c.Stderr
}
if c.Cmd.WaitDelay == 0 {
c.Cmd.WaitDelay = time.Second
}
if c.Cmd.SysProcAttr == nil {
c.Cmd.SysProcAttr = &syscall.SysProcAttr{}
}
c.Cmd.SysProcAttr.Setpgid = true
// Chapter 48: the parent-death signal, so a server does not outlive a
// daemon that died by SIGKILL. The kernel ties it to the thread that
// forked, not to the process (PR_SET_PDEATHSIG(2const): "the parent
// thread"), so the goroutine that starts the child locks its thread and
// keeps it until the child has exited: the thread cannot die while the
// server is healthy, and the signal fires only when every thread of the
// daemon is gone. The signal reaches the child only: a descendant of the
// server is outside it, and one that calls setsid is outside the process
// group's kill as well (Close kills the group; a daemon that dies by
// SIGKILL never runs Close). Those stay stated limits.
pdeathsig(c.Cmd.SysProcAttr)
c.wait = make(chan error, 1)
started := make(chan error, 1)
go func() {
runtime.LockOSThread()
err := c.Cmd.Start()
started <- err
if err != nil {
return
}
c.wait <- c.Cmd.Wait()
}()
if err := <-started; err != nil {
return err
}
c.stdin = stdin
c.conn = newConn(stdout, stdin, c.Stderr)
return nil
}
func (c *Command) Call(ctx context.Context, req mcp.Message) (mcp.Message, error) {
if c.conn == nil {
return mcp.Message{}, errors.New("mcp/stdio: the command was not started")
}
return c.conn.Call(ctx, req)
}
func (c *Command) Notify(ctx context.Context, n mcp.Message) error {
if c.conn == nil {
return errors.New("mcp/stdio: the command was not started")
}
return c.conn.Notify(ctx, n)
}
// Close: stdin closed, a grace for the exit, then SIGKILL to the child's
// process group. A server that had to be killed is not an error of the
// transport (the specification's shutdown order ends in SIGKILL); Killed
// reports it, and Close returns only an error the child raised on its own
// (its exit status; not exec.ErrWaitDelay, which says a descendant outside
// the group kept a pipe open after the child was gone).
func (c *Command) Close() error {
var err error
c.once.Do(func() {
if c.stdin == nil {
return
}
c.stdin.Close()
grace := c.Grace
if grace == 0 {
grace = 2 * time.Second
}
select {
case err = <-c.wait:
case <-time.After(grace):
c.killed = true
// The child was started in its own process group (Start), so
// the kill reaches a server that is a shell script and the
// children it spawned: a grandchild left holding our end of
// stdout would otherwise keep the reader goroutine alive.
_ = syscall.Kill(-c.Cmd.Process.Pid, syscall.SIGKILL)
<-c.wait
err = nil
}
if errors.Is(err, exec.ErrWaitDelay) {
err = nil
}
<-c.conn.done
})
return err
}
// Killed reports whether Close had to kill the server after Grace.
func (c *Command) Killed() bool { return c.killed }
// Pid is the child's pid, for a test that checks the process is gone.
func (c *Command) Pid() int {
if c.Cmd == nil || c.Cmd.Process == nil {
return 0
}
return c.Cmd.Process.Pid
}
The same framing runs over any reliable byte stream, and the specification says to reuse it: “Custom transports that run over a reliable bidirectional byte stream (e.g., Unix domain sockets or TCP) SHOULD reuse the stdio framing rather than defining a new one”. Socket dials a Unix socket and uses conn unchanged; ServeListener accepts connections, runs Serve on each after a check hook that the daemon sets to chapter 40’s SO_PEERCRED test, and closes every accepted connection when its context ends. Pipe is the in-memory form, which reads and writes each message through the real framing so the fixtures exercise the codec without a process or a socket.
// Socket dials a Unix socket that speaks the stdio framing: the daemon's
// Dir/mcp.sock. The directory's mode and the daemon's SO_PEERCRED check
// are the authentication; this client sends no token.
type Socket struct {
Path string
Log io.Writer // where a broken stream is noted; nil discards (the daemon passes its log)
c net.Conn
conn *conn
}
func (s *Socket) Dial(ctx context.Context) error {
var d net.Dialer
c, err := d.DialContext(ctx, "unix", s.Path)
if err != nil {
return err
}
s.c = c
s.conn = newConn(c, c, s.Log)
return nil
}
func (s *Socket) Call(ctx context.Context, req mcp.Message) (mcp.Message, error) {
if s.conn == nil {
return mcp.Message{}, errors.New("mcp/stdio: the socket was not dialled")
}
return s.conn.Call(ctx, req)
}
func (s *Socket) Notify(ctx context.Context, n mcp.Message) error {
if s.conn == nil {
return errors.New("mcp/stdio: the socket was not dialled")
}
return s.conn.Notify(ctx, n)
}
func (s *Socket) Close() error {
if s.c == nil {
return nil
}
err := s.c.Close()
<-s.conn.done
return err
}
// Pipe is the in-memory transport: a request is encoded to a line, read
// back with ReadMessage, handled, and the reply encoded and read back the
// same way, so the conformance fixtures exercise the codec and the server
// without a process or a socket. Raw sends one line as the client wrote
// it, for the fixtures that test the framing itself.
type Pipe struct {
Server *mcp.Server
// Handle, when set, replaces Server.Handle (the lab's own).
Handle func(ctx context.Context, m mcp.Message) mcp.Message
}
func (p *Pipe) handle(ctx context.Context, m mcp.Message) mcp.Message {
if p.Handle != nil {
return p.Handle(ctx, m)
}
return p.Server.Handle(ctx, m)
}
func (p *Pipe) Call(ctx context.Context, req mcp.Message) (mcp.Message, error) {
var line bytes.Buffer
if err := WriteMessage(&line, req); err != nil {
return mcp.Message{}, err
}
return p.Raw(ctx, line.Bytes())
}
// Raw delivers one raw line to the server side and returns what it wrote,
// as a client would read it; a framing error on the way in is answered
// with its code and no id, as Serve answers it.
func (p *Pipe) Raw(ctx context.Context, line []byte) (mcp.Message, error) {
in, err := ReadMessage(bufio.NewReader(bytes.NewReader(line)))
var reply mcp.Message
if err != nil {
var fe *FramingError
if !errors.As(err, &fe) {
return mcp.Message{}, err
}
reply = mcp.Message{JSONRPC: mcp.JSONRPCVersion, Error: &mcp.Error{Code: fe.ErrorCode(), Message: fe.Reason}}
} else {
reply = p.handle(ctx, in)
}
if reply.JSONRPC == "" {
return mcp.Message{}, nil // a notification: nothing written
}
var out bytes.Buffer
if err := WriteMessage(&out, reply); err != nil {
return mcp.Message{}, err
}
return ReadMessage(bufio.NewReader(&out))
}
func (p *Pipe) Notify(ctx context.Context, n mcp.Message) error {
_, err := p.Call(ctx, n)
return err
}
func (p *Pipe) Close() error { return nil }
Streamable HTTP, without sessions
Each message is its own POST to one endpoint. A notification is answered 202 with no body. A request is answered with “either Content-Type: application/json (a single JSON object) or Content-Type: text/event-stream (an SSE response stream). The client MUST support both.” This server answers every request as one JSON object, which the specification permits; the client reads both, and readSSE is chapter 24’s reader shape (lines, a blank line ends an event, data: lines accumulate) with a response-by-id filter on top. There is no Mcp-Session-Id, no GET stream, no Last-Event-ID: key change 9 removed resumability, so a stream that ends before the response loses the request, and the client’s answer is ErrStreamBroken, whose text says to re-issue it with a new id.
// Handler serves one mcp.Server at one endpoint. A TCP listener has no
// peer uid, so the handler carries what the Unix socket gets from the
// kernel: Token is the bearer token every request must present (compared
// in constant time; "" means no token is required, which only a test may
// choose: aecd mcp -http refuses to start without one), Hosts is the Host
// allowlist (nil: 127.0.0.1, localhost and [::1], any port; a Host not
// listed is 421 Misdirected Request, the DNS-rebinding rule applied to the
// request line), Origins the Origin allowlist (an absent Origin is
// accepted: a non-browser client sends none; a present one not listed is
// 403). MaxBody caps a request (default 4 MiB). The HTTP status of a
// JSON-RPC error follows the specification: 400 for a missing or
// mismatched header (-32020), an unsupported version (-32022), a missing
// _meta field (-32602 with data.field) and a parse or shape error; 404 for
// an unknown method (-32601); 200 for every other error, which is the
// method's answer.
type Handler struct {
Server *mcp.Server
Token string
Hosts []string
Origins []string
MaxBody int64
running atomic.Int64 // requests being handled, against mcp.MaxInFlight
}
// defaultHosts are the loopback names a local server answers to.
var defaultHosts = []string{"127.0.0.1", "localhost", "[::1]"}
// hostAllowed compares the Host header's name part (the port is dropped)
// with the allowlist, case-insensitively.
func (h *Handler) hostAllowed(host string) bool {
name := host
if i := strings.LastIndex(host, ":"); i >= 0 && !strings.HasSuffix(host, "]") {
name = host[:i]
}
list := h.Hosts
if list == nil {
list = defaultHosts
}
for _, a := range list {
if strings.EqualFold(a, name) {
return true
}
}
return false
}
// tokenOK is a constant-time comparison of the bearer token.
func (h *Handler) tokenOK(r *http.Request) bool {
if h.Token == "" {
return true
}
auth := r.Header.Get("Authorization")
const prefix = "Bearer "
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return false
}
return subtle.ConstantTimeCompare([]byte(auth[len(prefix):]), []byte(h.Token)) == 1
}
// The methods whose Mcp-Name header is required, and the body field it
// mirrors (streamable-http#standard-request-headers).
var nameField = map[string]string{"tools/call": "name", "resources/read": "uri", "prompts/get": "name"}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
// GET and DELETE belonged to the 2025-03-26..2025-11-25 shape.
w.Header().Set("Allow", "POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !h.hostAllowed(r.Host) {
h.errorStatus(w, http.StatusMisdirectedRequest, nil, mcp.InvalidRequest, "host not allowed")
return
}
if o := r.Header.Get("Origin"); o != "" && !h.originAllowed(o) {
h.errorStatus(w, http.StatusForbidden, nil, mcp.InvalidRequest, "origin not allowed")
return
}
if !h.tokenOK(r) {
w.Header().Set("WWW-Authenticate", "Bearer")
h.errorStatus(w, http.StatusUnauthorized, nil, mcp.InvalidRequest, "a bearer token is required")
return
}
if ct, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); ct != "application/json" {
h.errorStatus(w, http.StatusBadRequest, nil, mcp.InvalidRequest, "Content-Type must be application/json")
return
}
accept := r.Header.Get("Accept")
if !strings.Contains(accept, "application/json") || !strings.Contains(accept, "text/event-stream") {
h.errorStatus(w, http.StatusBadRequest, nil, mcp.InvalidRequest, "Accept must list application/json and text/event-stream")
return
}
max := h.MaxBody
if max == 0 {
max = 4 << 20
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, max))
if err != nil {
h.errorStatus(w, http.StatusRequestEntityTooLarge, nil, mcp.InvalidRequest, "body too large")
return
}
m, err := mcp.DecodeMessage(body)
if err != nil {
code, msg := mcp.ParseError, "the body is not JSON"
var se *mcp.ShapeError
if errors.As(err, &se) {
code, msg = mcp.InvalidRequest, se.Reason
}
h.errorStatus(w, http.StatusBadRequest, nil, code, msg)
return
}
switch m.Classify() {
case mcp.KindNotification:
w.WriteHeader(http.StatusAccepted)
return
case mcp.KindRequest:
default:
h.errorStatus(w, http.StatusBadRequest, m.ID, mcp.InvalidRequest, "the body must be a request or a notification")
return
}
params, err := mcp.DecodeParams(m.Params)
if err != nil {
h.errorStatus(w, http.StatusBadRequest, m.ID, mcp.InvalidParams, err.Error())
return
}
if code, msg := h.checkHeaders(r, m, params); msg != "" {
h.errorStatus(w, http.StatusBadRequest, m.ID, code, msg)
return
}
if h.running.Add(1) > mcp.MaxInFlight {
h.running.Add(-1)
h.errorStatus(w, http.StatusServiceUnavailable, m.ID, mcp.InternalError, fmt.Sprintf("too many requests in flight (the limit is %d)", mcp.MaxInFlight))
return
}
defer h.running.Add(-1)
reply := h.Server.Handle(r.Context(), m)
status := http.StatusOK
if reply.Error != nil {
switch reply.Error.Code {
case mcp.MethodNotFound:
status = http.StatusNotFound
case mcp.UnsupportedProtocolVersion, mcp.HeaderMismatch, mcp.MissingRequiredClientCapability, mcp.ParseError, mcp.InvalidRequest:
status = http.StatusBadRequest
case mcp.InvalidParams:
if bytes.Contains(reply.Error.Data, []byte(`"field"`)) {
status = http.StatusBadRequest
}
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(reply)
}
// checkHeaders is streamable-http#server-validation: MCP-Protocol-Version
// equal to _meta's, Mcp-Method equal to method, Mcp-Name equal to the
// name or uri for the methods that have one (after decoding the base64
// sentinel), and every recognised Mcp-Param-{Name} equal to the argument
// it mirrors. It reads the params that ServeHTTP decoded with
// mcp.DecodeParams, the decoding Server.Handle runs the method from, by
// exact member name: a check that read the body another way (a decoder that
// folds case, or takes the first of two keys) could pass the header of one
// tool and run another, which is the attack the MUST exists for.
func (h *Handler) checkHeaders(r *http.Request, m mcp.Message, params mcp.Params) (int, string) {
version := params.Meta.ProtocolVersion
hv := r.Header.Get("MCP-Protocol-Version")
switch {
case hv == "":
return mcp.HeaderMismatch, "MCP-Protocol-Version header missing"
case version != "" && hv != version:
return mcp.HeaderMismatch, "MCP-Protocol-Version header does not match _meta"
// version == "": _meta lacks the field, which Handle answers with
// InvalidParams (basic/index#_meta), the base protocol's rule.
}
switch hm := r.Header.Get("Mcp-Method"); {
case hm == "":
return mcp.HeaderMismatch, "Mcp-Method header missing"
case hm != m.Method:
return mcp.HeaderMismatch, "Mcp-Method header does not match the body"
}
name := params.String("name")
if field, ok := nameField[m.Method]; ok {
want := name
if field == "uri" {
want = params.String("uri")
}
raw := r.Header.Get("Mcp-Name")
if raw == "" {
return mcp.HeaderMismatch, "Mcp-Name header missing"
}
got, err := mcp.DecodeHeaderValue(raw)
if err != nil || got != want {
return mcp.HeaderMismatch, "Mcp-Name header does not match the body"
}
}
if m.Method == "tools/call" {
args := params.Arguments()
for _, t := range h.Server.Tools {
if t.Tool.Name != name {
continue
}
hps, err := mcp.HeaderParams(t.Tool.InputSchema)
if err != nil {
break
}
for _, hp := range hps {
raw := r.Header.Get("Mcp-Param-" + hp.Name)
want, present := mcp.HeaderValue(args, hp.Path)
if raw == "" {
if present {
return mcp.HeaderMismatch, "Mcp-Param-" + hp.Name + " header missing"
}
continue
}
got, err := mcp.DecodeHeaderValue(raw)
if err != nil || !present || got != want {
return mcp.HeaderMismatch, "Mcp-Param-" + hp.Name + " header does not match the body"
}
}
}
}
return 0, ""
}
func (h *Handler) originAllowed(o string) bool {
for _, a := range h.Origins {
if strings.EqualFold(a, o) {
return true
}
}
return false
}
func (h *Handler) errorStatus(w http.ResponseWriter, status int, id *mcp.ID, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
// An id that is nil or null is not written (Message.MarshalJSON).
_ = json.NewEncoder(w).Encode(mcp.Message{JSONRPC: mcp.JSONRPCVersion, ID: id, Error: &mcp.Error{Code: code, Message: msg}})
}
The handler’s checks run in an order that puts the cheap and the security-relevant ones first. A method other than POST is 405. A Host outside the allowlist is 421. An Origin that is present and not allowed is 403: the specification’s “Servers MUST validate the Origin header on all incoming connections to prevent DNS rebinding attacks”, whose failure is “HTTP 403 Forbidden”. A missing or wrong bearer token is 401 with WWW-Authenticate: Bearer. The Host check and the token are this server’s, not the specification’s, and the handler’s comment says so: a TCP listener has no peer uid, so it carries what the Unix socket gets from the kernel. The specification asks only that servers “SHOULD bind only to localhost (127.0.0.1) rather than all network interfaces” and “SHOULD implement proper authentication for all connections”. Host is the second half of the rebinding defence: a page at an attacker’s name that resolves to 127.0.0.1 sends that name in Host, and the default allowlist is 127.0.0.1, localhost and [::1], any port. The token is compared in constant time, and aecd mcp -http will not start without one. Then Content-Type and Accept are checked (this server’s choice again), the body is read under a 4 MiB cap (413), decoded, classified, and its params decoded once.
The transport mirrors three body fields into headers, so that “intermediaries (load balancers, gateways, observability tooling) can route and inspect requests without parsing the body”: MCP-Protocol-Version (equal to _meta’s), Mcp-Method (equal to method) and, for tools/call, resources/read and prompts/get, Mcp-Name (the tool name or the resource URI). A tool’s schema can add more with x-mcp-header, which makes the named property travel as Mcp-Param-{name}. Mirroring creates a rule, and the rule is a security rule: “Servers that process the request body MUST reject requests where the values specified in the headers do not match the corresponding values in the request body. This prevents potential security vulnerabilities when different components in the network rely on different sources of truth (e.g., a load balancer routing on the header value while the MCP server executes based on the body value).” A mismatch is -32020 with status 400, and checkHeaders is the check.
The rule is only as strong as the agreement between the thing that checks and the thing that executes, and the first version of this code broke it. checkHeaders decoded params into a struct, which encoding/json matches case-insensitively and in which the last of two equal keys wins, while Handle read the body into a map by exact key. A body {"name":"write_file","NAME":"read_file", …} with Mcp-Name: read_file passed the header check, and write_file ran. The same bytes with ARGUMENTS and arguments made the mirrored parameter and the executed one differ. Both are the load-balancer attack, with the load balancer’s job done by this handler. The fix is not a better check but one decoding: mcp.DecodeParams reads the params once, by exact member name, and both the header check and the method handler use its result, while Message.UnmarshalJSON already refuses a repeated member name. TestHeadersAndExecutionReadOneBody runs the two probes in both directions, with a repeated key, a mismatched Mcp-Name and a case-variant _meta key.
// HeaderParam is one argument a Streamable HTTP client mirrors into an
// Mcp-Param-{Name} header: the chain of properties keys to it and the
// header name the schema's x-mcp-header gave.
type HeaderParam struct {
Path []string
Name string
}
// tchar is RFC 9110 §5.6.2's token character set, the only characters an
// x-mcp-header name may hold (streamable-http#schema-extension).
var tchar = regexp.MustCompile(`^[!#$%&'*+\-.^_` + "`" + `|~0-9A-Za-z]+$`)
// ToolNamePattern is server/tools#tool-names: 1 to 128 characters of
// letters, digits, underscore, hyphen and dot. The specification says
// SHOULD; this client treats it as a condition of mounting, because the
// name becomes part of an agent.Tool's name and reaches the model.
var ToolNamePattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
// HeaderParams walks inputSchema for x-mcp-header annotations and applies
// the rules of basic/transports/streamable-http#schema-extension: a value
// is non-empty, token syntax, no control characters, case-insensitively
// unique, on a property of type integer, string or boolean (never number),
// and reachable from the root through properties keys only. An annotation
// anywhere else (under items, a composition or conditional keyword, $ref,
// $defs, additionalProperties or patternProperties) makes the definition
// invalid, and the error names the offending path.
func HeaderParams(inputSchema json.RawMessage) ([]HeaderParam, error) {
var root map[string]any
if err := json.Unmarshal(inputSchema, &root); err != nil {
return nil, fmt.Errorf("inputSchema is not an object: %w", err)
}
var out []HeaderParam
seen := map[string]string{}
var walk func(node map[string]any, path []string, reachable bool) error
walk = func(node map[string]any, path []string, reachable bool) error {
for k, v := range node {
switch k {
case "x-mcp-header":
name, ok := v.(string)
where := "/" + strings.Join(path, "/")
switch {
case !ok:
return fmt.Errorf("x-mcp-header at %s is not a string", where)
case !reachable:
return fmt.Errorf("x-mcp-header at %s is not statically reachable through properties keys", where)
case name == "":
return fmt.Errorf("x-mcp-header at %s is empty", where)
case !tchar.MatchString(name):
return fmt.Errorf("x-mcp-header %q at %s is not an HTTP token", name, where)
}
if prev, dup := seen[strings.ToLower(name)]; dup {
return fmt.Errorf("x-mcp-header %q at %s repeats %s", name, where, prev)
}
t, _ := node["type"].(string)
switch t {
case "integer", "string", "boolean":
default:
return fmt.Errorf("x-mcp-header %q at %s is on a property of type %q, not integer, string or boolean", name, where, t)
}
seen[strings.ToLower(name)] = where
out = append(out, HeaderParam{Path: append([]string(nil), path...), Name: name})
case "properties":
props, ok := v.(map[string]any)
if !ok {
continue
}
for pname, pv := range props {
child, ok := pv.(map[string]any)
if !ok {
continue
}
if err := walk(child, append(append([]string(nil), path...), pname), reachable); err != nil {
return err
}
}
default:
// Anything else that holds subschemas is not a properties
// chain: items, prefixItems, anyOf, oneOf, allOf, not, if,
// then, else, $defs, definitions, additionalProperties,
// patternProperties, dependentSchemas.
switch child := v.(type) {
case map[string]any:
if err := walk(child, append(append([]string(nil), path...), k), false); err != nil {
return err
}
case []any:
for i, e := range child {
if m, ok := e.(map[string]any); ok {
if err := walk(m, append(append([]string(nil), path...), fmt.Sprintf("%s[%d]", k, i)), false); err != nil {
return err
}
}
}
}
}
}
return nil
}
if err := walk(root, nil, true); err != nil {
return nil, err
}
return out, nil
}
// EncodeHeaderValue applies streamable-http#value-encoding: a value of
// visible ASCII, space and tab with no leading or trailing whitespace goes
// as is; anything else, and any plain value that itself matches the
// sentinel, is "=?base64?" + base64(UTF-8) + "?=".
func EncodeHeaderValue(s string) string {
if headerSafe(s) && !isSentinel(s) {
return s
}
return "=?base64?" + base64.StdEncoding.EncodeToString([]byte(s)) + "?="
}
Left off the page: DecodeHeaderValue, the inverse the handler’s checkHeaders applies, with isSentinel and headerSafe, the two predicates EncodeHeaderValue uses (TestHeaderValueEncoding, the specification’s own table both ways); HeaderValue, which renders an argument as a header’s text, strings as they are, integers in decimal, booleans as true and false, and omits a value that is not a primitive (TestHeaderParams); and UnsafeHeaderInteger and MaxSafeInteger, below (TestClientRefusesAnIntegerOutsideTheSafeRange).
x-mcp-header has six constraints, and HeaderParams applies them, with one clause tested at the call instead (the fifth also requires an integer value to lie in the safe range for JavaScript, -2^53+1 to 2^53-1; the clause constrains a value, so the schema cannot show it: the client refuses a call whose mirrored argument is a number outside the range, before anything is sent, UnsafeHeaderInteger, TestClientRefusesAnIntegerOutsideTheSafeRange): the name is not empty; it matches the HTTP field-name token syntax (RFC 9110 §5.1); it holds no control character; it is unique case-insensitively among the schema’s annotations; it sits on a property of type integer, string or boolean and never number; and the property is “statically reachable” from the schema root, by “a chain consisting solely of properties keys”, never through items, a composition keyword, a conditional keyword or $ref. The last has a reason, as this chapter reads it. A client mirrors the value at the property’s exact path, and a path through an array names no single value; an annotation inside a oneOf branch might or might not apply to a given call. For all six the specification’s verdict is that “Clients using the Streamable HTTP transport MUST reject tool definitions where any x-mcp-header value violates these constraints”, and “reject” means to “exclude the invalid tool from the result of tools/list”. The code excludes the tool rather than mounting it without the header, and the reason is a routing one: a tool mounted without its routing header would reach a different backend from the one its definition says. “Clients using other transports (e.g., stdio) MAY ignore x-mcp-header annotations entirely”, which is why Mount applies HeaderParams only when the transport implements HeaderMirroring. The value encoding is the other half: a value of visible ASCII, space and tab with no leading or trailing whitespace goes as it is, and anything else, and any plain value that itself looks like the sentinel, goes as =?base64? + the base64 of its UTF-8 + ?=. TestClientAgainstHandler sends Hello, 世界 and the handler sees Mcp-Param-Greeting: =?base64?SGVsbG8sIOS4lueVjA==?=, the specification’s own example.
// Client is the Streamable HTTP client: one POST per message with the
// Accept header the specification requires, the three standard headers
// mirrored from the body, Mcp-Param-* from the tool definitions Mount
// registered, a bearer token read from TokenEnv at each request (never
// stored, never logged; a daemon with a secrets block, chapter 48, sets
// Token from the value it read at Open instead, and that is used), no proxy
// and no redirects. A JSON reply is
// decoded; an SSE reply is read event by event until the response with
// the request's id; a stream that breaks before it is an error the caller
// re-issues with a new id (there is no resumption).
type Client struct {
URL string
TokenEnv string
Token string // chapter 48: the broker's value; when set it is used in place of reading TokenEnv
HTTP *http.Client
Origin string // sent as Origin when set (a browser-like client); "" sends none
mu sync.Mutex
params map[string][]mcp.HeaderParam
}
func (c *Client) MirrorsHeaders() bool { return true }
func (c *Client) SetHeaderParams(tool string, params []mcp.HeaderParam) {
c.mu.Lock()
defer c.mu.Unlock()
if c.params == nil {
c.params = map[string][]mcp.HeaderParam{}
}
c.params[tool] = params
}
func (c *Client) client() *http.Client {
c.mu.Lock()
defer c.mu.Unlock()
if c.HTTP != nil {
return c.HTTP
}
c.HTTP = &http.Client{
Transport: &http.Transport{Proxy: nil},
Timeout: 5 * time.Minute,
CheckRedirect: func(*http.Request, []*http.Request) error {
return errors.New("mcp/streamable: redirects are refused")
},
}
return c.HTTP
}
func (c *Client) Call(ctx context.Context, req mcp.Message) (mcp.Message, error) {
if req.Classify() != mcp.KindRequest {
return mcp.Message{}, errors.New("mcp/streamable: Call takes a request")
}
resp, err := c.post(ctx, req)
if err != nil {
return mcp.Message{}, err
}
defer resp.Body.Close()
ct, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
switch {
case ct == "application/json":
body, err := io.ReadAll(io.LimitReader(resp.Body, MaxResponseBytes+1))
if err != nil {
return mcp.Message{}, fmt.Errorf("mcp/streamable: HTTP %d: reading the body: %v", resp.StatusCode, mcp.Clean(err.Error(), 200))
}
if len(body) > MaxResponseBytes {
return mcp.Message{}, fmt.Errorf("mcp/streamable: HTTP %d: the reply is longer than %d bytes (MaxResponseBytes)", resp.StatusCode, MaxResponseBytes)
}
m, err := mcp.DecodeMessage(body)
if err != nil {
return mcp.Message{}, fmt.Errorf("mcp/streamable: HTTP %d with a body that is not a message: %v", resp.StatusCode, mcp.Clean(err.Error(), 200))
}
if resp.StatusCode != http.StatusOK && m.Error == nil {
return mcp.Message{}, fmt.Errorf("mcp/streamable: HTTP %d without a JSON-RPC error", resp.StatusCode)
}
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden, http.StatusMisdirectedRequest:
// The transport refused us before the protocol spoke: not a
// protocol error, and never a reason to think the server legacy.
// The message is the server's text, so it is cleaned and cut
// here and fenced again where it reaches a model.
return mcp.Message{}, fmt.Errorf("mcp/streamable: HTTP %d: %s", resp.StatusCode, mcp.Clean(m.Error.Message, mcp.MaxErrorTextBytes))
}
return m, nil
case ct == "text/event-stream" && resp.StatusCode == http.StatusOK:
return readSSE(resp.Body, *req.ID)
}
return mcp.Message{}, fmt.Errorf("mcp/streamable: HTTP %d with Content-Type %q", resp.StatusCode, resp.Header.Get("Content-Type"))
}
func (c *Client) Notify(ctx context.Context, n mcp.Message) error {
if n.Classify() != mcp.KindNotification {
return errors.New("mcp/streamable: Notify takes a notification")
}
resp, err := c.post(ctx, n)
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode != http.StatusAccepted {
return fmt.Errorf("mcp/streamable: a notification was answered HTTP %d, not 202", resp.StatusCode)
}
return nil
}
func (c *Client) Close() error {
if c.HTTP != nil {
c.HTTP.CloseIdleConnections()
}
return nil
}
// CheckURL is the rule for a server URL, for a configuration to apply before
// a client is built: http or https with a host, no credentials in it and no
// query or fragment. A credential belongs in the token variable, never in a
// URL that is logged, printed in errors and sent in a Referer-like place; a
// query is how a secret gets into one. The errors it returns do not repeat
// the URL.
func CheckURL(raw string) error {
_, err := parseURL(raw)
return err
}
func parseURL(raw string) (*url.URL, error) {
u, err := url.Parse(raw)
switch {
case err != nil:
return nil, errors.New("mcp/streamable: the server URL does not parse")
case u.Scheme != "http" && u.Scheme != "https":
return nil, errors.New("mcp/streamable: the server URL must be http or https")
case u.Hostname() == "":
return nil, errors.New("mcp/streamable: the server URL has no host")
case u.User != nil:
return nil, errors.New("mcp/streamable: the server URL carries credentials; use token_env")
case u.RawQuery != "" || u.ForceQuery || u.Fragment != "":
return nil, errors.New("mcp/streamable: the server URL carries a query or fragment")
}
return u, nil
}
// loopbackHost: localhost, or an address in 127.0.0.0/8 or ::1.
func loopbackHost(h string) bool {
if strings.EqualFold(h, "localhost") {
return true
}
ip := net.ParseIP(h)
return ip != nil && ip.IsLoopback()
}
// post builds the request with the headers streamable-http#client-behavior
// lists.
func (c *Client) post(ctx context.Context, m mcp.Message) (*http.Response, error) {
u, err := parseURL(c.URL)
if err != nil {
return nil, err
}
body, err := json.Marshal(m)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
if c.Origin != "" {
req.Header.Set("Origin", c.Origin)
}
if c.TokenEnv != "" || c.Token != "" {
tok := c.Token
if tok == "" {
tok = os.Getenv(c.TokenEnv)
}
if tok != "" {
if u.Scheme != "https" && !loopbackHost(u.Hostname()) {
return nil, errors.New("mcp/streamable: refusing to send a bearer token over cleartext http to a host that is not loopback")
}
req.Header.Set("Authorization", "Bearer "+tok)
}
}
params, _ := mcp.DecodeParams(m.Params)
if m.Method != "" {
req.Header.Set("MCP-Protocol-Version", params.Meta.ProtocolVersion)
req.Header.Set("Mcp-Method", m.Method)
name := params.String("name")
if field, ok := nameField[m.Method]; ok {
v := name
if field == "uri" {
v = params.String("uri")
}
req.Header.Set("Mcp-Name", mcp.EncodeHeaderValue(v))
}
if m.Method == "tools/call" {
c.mu.Lock()
hps := c.params[name]
c.mu.Unlock()
args := params.Arguments()
for _, hp := range hps {
if mcp.UnsafeHeaderInteger(args, hp.Path) {
return nil, fmt.Errorf("mcp/streamable: argument %s is a number outside +-(2^53-1), which an x-mcp-header integer MUST NOT be", strings.Join(hp.Path, "."))
}
if v, ok := mcp.HeaderValue(args, hp.Path); ok {
req.Header.Set("Mcp-Param-"+hp.Name, mcp.EncodeHeaderValue(v))
}
}
}
}
return c.client().Do(req)
}
// ErrStreamBroken is an SSE reply that ended before the response.
var ErrStreamBroken = errors.New("mcp/streamable: the response stream ended before the response; re-issue the request with a new id")
The client takes the precautions a client of a hostile server needs. It uses no proxy from the environment and refuses every redirect (a 302 would send the bearer token wherever the server points). It reads the token from the variable token_env names, at each request, and never stores or logs it (a daemon with a secrets block, chapter 48, reads it once at Open and gives the client that value instead). It will not send the token over cleartext http to a host that is not loopback, and CheckURL refuses a URL that carries credentials, a query or a fragment, since a secret in a URL ends up in logs and errors. A 401, 403 or 421 is returned as a transport error naming the status, never mistaken for the protocol speaking, and so never for a legacy server.
What a server can make the model read, and what it can make the daemon carry
A mounted tool is a foreign program’s output going into a model’s context, and the specification’s own sentence about trust is short: “descriptions of tool behavior such as annotations should be considered untrusted, unless obtained from a trusted server” (the specification’s overview, “Tool Safety”). The schema is blunter about annotations: “Clients should never make tool use decisions based on ToolAnnotations received from untrusted servers.” Trust is the lever, and it is per server, from configuration. An Untrusted server’s every call is Marked: chapter 27’s approval protocol applies, with a reason that names the server (mcp server book is untrusted: greet needs approval), silence is a timeout, and under a nil Approver the call is denied, which TestMountedIntoSession shows by running the same script against a trusted and an untrusted mount. An untrusted tool also never runs unattended, since chapter 42’s scheduler refuses a marked call at once. Its annotations decide nothing. A Trusted server’s calls run unmarked, and its readOnlyHint makes the tool Idempotent.
Only readOnlyHint. The first version also let idempotentHint make a tool Idempotent, and the schema says what the hint is: idempotentHint (“If true, calling the tool repeatedly with the same arguments will have no additional effect on its environment”) is, in the schema’s words, “meaningful only when readOnlyHint == false”. It describes a write that is safe to repeat. Chapter 26’s loop reads Idempotent as permission to answer a repeated call in a run from the first call’s result, and such a call does not advance the loop’s write generation: the contract of a read. A review drove the loop against a trusted one-cell server whose get was readOnlyHint and whose set was idempotentHint only, with the script get, set(“new”), get, set(“other”), set(“new”). The loop answered the second get from its cache after set("new"), so the model saw old again, and it answered the repeated set("new") from its cache too, so that write never ran while the model was told it had: a stale read, and a write that did not happen. TestIdempotentHintDoesNotCacheAWrite is that script, and its expectation is c1=old c2=set to new c3=new c4=set to other c5=set to new, with set run three times and the cell left at new. What remains is a decision, stated: chapter 40’s resume rule marks an in-flight Idempotent call for replay whatever ResumePolicy says (the turn is erased and runs again when it is next sent), so a Trusted server’s readOnlyHint tool is replayed. That is what Idempotent means for the daemon’s own read tools, and the cost of a Trusted server that lies about readOnlyHint is a replayed call after a crash.
Every string a server controls reaches the model through the same fence. A result’s text, an isError result’s text, a JSON-RPC error’s message, a transport error (an HTTP refusal’s body included), the keys of an input request, and a resource’s URI used as a label are each cleaned (control characters escaped, so a stray ESC cannot clear a terminal), cut to a bound, and quoted by prompt.Quote under the tool’s name. The fence is chapter 30’s: <<<NAME … NAME>>>, the run of angle brackets starting at three and growing until neither fence occurs in the text, so no text closes the block early; a look-alike close in a server’s answer only widens the fence. TestEveryServerTextIsFenced sends ten paths each a look-alike close, a look-alike open, an ESC and a BEL. The same fence in the captured turn’s session file, below, is <<<book__greet … book__greet>>>. The fence applies whatever the server’s trust: Trust decides Marked and the annotations, nothing about the fence.
// cutBytes returns s cut to at most max bytes at a character boundary, and
// how many bytes were dropped.
func cutBytes(s string, max int) (string, int) {
if len(s) <= max {
return s, 0
}
n := max
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n], len(s) - n
}
// Clean makes a server's text safe to print on one line: cut to max bytes
// (a marker says how many were dropped), and every control character
// (newline and tab included), format character (bidirectional overrides,
// zero-width) and invalid byte written as a visible escape. It is the form
// of every name, reason and message of a server that a log or a status
// line shows.
func Clean(s string, max int) string {
s, dropped := cutBytes(s, max)
out := escape(s, false)
if dropped > 0 {
out += fmt.Sprintf("[%d more bytes cut]", dropped)
}
return out
}
// sanitize is Clean for text of many lines: newline and tab stay, the rest
// is escaped as Clean does, and the cut is reported by the caller.
func sanitize(s string) string { return escape(s, true) }
func escape(s string, multiline bool) string {
var b strings.Builder
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
switch {
case r == utf8.RuneError && size == 1:
fmt.Fprintf(&b, `\x%02x`, s[i])
case multiline && (r == '\n' || r == '\t'):
b.WriteRune(r)
case r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0):
fmt.Fprintf(&b, `\x%02x`, r)
case unicode.Is(unicode.Cf, r) || r == 0x2028 || r == 0x2029:
fmt.Fprintf(&b, `\u%04x`, r)
default:
b.WriteString(s[i : i+size])
}
i += size
}
return b.String()
}
Two strings cannot be fenced. A tool’s description, and the description, title and enum strings inside its inputSchema, are the tool spec: the model reads them as the definition of what it may call, and there is nowhere to put a fence around the definition of the thing the fence protects. What bounds them is size: a description over 8 KiB (MaxDescriptionBytes) or a schema over 32 KiB (MaxSchemaBytes) excludes the tool, and control characters in a description are escaped. What they say is not bounded, and a description that reads “ignore the system prompt” is read as a tool description. For an untrusted server’s own tools the consequence of obeying it is a request for approval, not an action, which is the point of marking every call; a description can still steer the model toward other tools, and those answer to their own rules. For a trusted server there is no such stop, and trust is the configuration’s claim that the server’s author is not hostile. Chapter 46’s corpus runs a poisoned description against this surface. A server’s instructions are the third text it controls, and the daemon logs them cut to 200 characters (the capture’s log has the line) and gives them to no model: TestMountInstructionsIgnored asserts they reach no tool description and no section of the system prompt.
An image is carried only if it is one. The four types are image/png, image/jpeg, image/gif and image/webp; the base64 must decode; the decoded bytes must start with that format’s signature (RIFF with WEBP at byte 8, for WebP); at most 4 MiB; and the data URL is built from the decoded bytes, not from the server’s string. Anything else is named in a line of text, as audio is (no fleet model takes audio). The check exists because an unchecked image failed every later request of a session: the Anthropic client returns an error at encode time for data that is not base64, and the part had already entered the session, so one bad block poisoned the session for good. A carried image is not routed to a vision model: chapter 28’s router reads the images of the last user message, so a tool result’s image goes to whichever model serves the turn.
Everything else a server can make the client carry is bounded by a named constant with its reason beside it, and a value over a bound is cut with a stated marker or refused with an error that names the server and the constant. The bounds are the table below. Each is a named constant, in internal/mcp or in a transport, with its reason in the comment beside it.
| Bound | Value | Why this value | Over it |
|---|---|---|---|
MaxObservationBytes |
64 KiB | about 16 thousand tokens, what an unsandboxed command tool keeps of one output stream | the text of a result as the model receives it, fences, labels, escapes and the cut line counted; cut after escaping, at a character boundary, and a line outside the fence says how many bytes and blocks were left out |
ObservationMarkerBytes |
256 | the line is 139 bytes of text and two integers of at most 20 digits, 179, rounded up | the room reserved for that line |
MaxResultBlocks |
64 | a result of 200,000 one-byte resources would cost the fence of each, more than the text | blocks of one result read; the rest are counted in the cut line |
MaxErrorTextBytes |
2 KiB | an error is read to be understood, not to be mined | each piece of server text in an error observation; cut, the marker outside the fence |
MaxDescriptionBytes |
8 KiB | sent with every model request, a standing cost; longer than the longest descriptions of the reference servers | the tool is excluded, the reason names the constant |
MaxSchemaBytes |
32 KiB | also a standing cost, and what chapter 25’s checker walks on every call | the tool is excluded |
MaxTools |
256 | a model offered more chooses badly before its context is full | the mount fails, the error naming the server and the constant: which 256 to keep is the principal’s decision |
MaxListPages |
32 | eight tools a page on average at MaxTools |
the mount fails; a repeated cursor fails it too |
MaxImageBytes |
4 MiB decoded | under the 5 MB per-image limit of the hosted vision APIs this book’s router can reach | the block is named in text; the bound is per block, and a result’s images are bounded in sum only by the transport (the stdio line, MaxResponseBytes) |
MaxInFlight |
64 | far more than a model’s tool calls in one turn, far below what exhausts a daemon | refused, not queued: InternalError under the id on stdio, 503 on HTTP |
MaxArgEnvBytes |
32 KiB | one ARG_ value; the call fails with a result naming the argument |
|
stdio.MaxLine |
16 MiB with its newline | an unbounded line is memory exhaustion from a peer | -32700, no id, the stream closed |
stdio.WriteTimeout |
30 s | far longer than a reading peer takes to drain a full line, short enough that a stuck peer costs one request’s time | the write fails, and the connection with it |
stdio.EOFGrace |
1 s | requests in flight after the end of input are cancelled | |
streamable.MaxResponseBytes, MaxEventBytes |
16 MiB each | the stdio line bound: one message is the same message on either transport | an error naming the constant |
streamable.MaxStreamBytes |
64 MiB | four full-size events; the client’s five-minute timeout bounds the duration, this bounds what it can be made to read in that time | an error naming the constant |
| the HTTP request body | 4 MiB | 413 |
|
| a command tool’s output | 64 KiB per stream | MaxObservationBytes |
the cut is stated in the result |
| a mounted server’s stderr | 4 KiB a line, 64 KiB a minute | 64 KiB is about eight hundred lines of eighty characters; a chatty server writes under 60 KiB a minute | the rest is counted, and one line says how much |
The bound with arithmetic behind it is the first. MaxObservationBytes is the bytes of every text part of a result as the model receives it; images are outside it, under their own bound (MaxImageBytes, at most MaxResultBlocks blocks read) and, in sum, under the transport’s 16 MiB line or MaxResponseBytes. Counting only the server’s text would have left holes, and the review found one: a result of resource blocks gave an observation of several megabytes, because the URI used as the fence’s label was never cut and prompt.Quote writes a label twice. The budget therefore includes the fences. A resource’s label is cleaned and cut to 256 bytes, so a resource with an empty body costs at most 3 + 256 + 1 bytes for the opening fence, 1 for the body’s newline and 256 + 3 for the closing one, 520, and one more for the separator the run adds; 64 of them in one run (MaxResultBlocks) are 64 × 520 bytes, 63 separators and the outer fence, 33,373 bytes under book__greet (ContentParts on wntrmute), about half the budget, so fences alone cannot exhaust it. A fence widens with the text it must not be closed by, so the amount of body that fits is found by cutting the excess and rendering again (at most 64 passes, then the run is dropped). When anything is cut, ObservationMarkerBytes bytes are reserved for the line that says so. TestObservationCap checks each shape at the bound (whole), one over (cut), at 2 MiB, with a 1 MiB URI, with a 7 MiB URI, with 200,000 one-byte resources and with 1 MiB of ESC, and requires len(observation) <= MaxObservationBytes every time.
The list walk is the other bound with a failure behind it. A server controls nextCursor, and a walk that follows it unconditionally never ends: against a server whose cursor never ran out, the first version issued requests as fast as the server answered and kept every page. ListTools stops at MaxListPages pages or MaxTools tools, treats a cursor it has already followed as a loop, and each is an ErrListLimit that Mount wraps with the server’s name; TestListWalkIsBounded covers an endless list, a cycle, and each bound at and one over, and TestEmptyCursorIsACursor the two cases the empty cursor adds: a server that answers "" for ever is a repeated cursor, ended on the second request, and one that answers "" once and then a new cursor on every page is ended at MaxListPages.
The daemon as a client: mounting at Open
aecd.json gains two keys. mcp is a list of servers to mount into every session (ServerConfig: a name that becomes the prefix, a transport of command, socket or http, and trust, absent meaning untrusted), and mcp_serve says what the daemon’s own server offers (ServeConfig, below).
// Transport carries one message each way. Call sends a request and returns
// the response that matches its id; Notify sends a notification and
// expects nothing back. A Transport that mirrors body fields into an
// envelope (Streamable HTTP) also implements HeaderMirroring, which Mount
// consults before accepting a tool whose schema carries x-mcp-header.
type Transport interface {
Call(ctx context.Context, req Message) (Message, error)
Notify(ctx context.Context, n Message) error
Close() error
}
// HeaderMirroring is implemented by a transport that mirrors Mcp-Name and
// Mcp-Param-* headers from the body (streamable.Client); such a client
// must refuse a tool definition whose x-mcp-header annotations are invalid
// (basic/transports/streamable-http#schema-extension).
type HeaderMirroring interface {
MirrorsHeaders() bool
// SetHeaderParams tells the transport which properties of a tool's
// arguments it mirrors, from the schema Mount checked.
SetHeaderParams(tool string, params []HeaderParam)
}
// Trust is the one policy knob this chapter owns: an Untrusted server's
// tools are all Marked (approval before every call, chapter 27) and their
// annotations are ignored; Trusted is configuration per server, earned by
// chapter 48's vetting.
type Trust int
const (
Untrusted Trust = iota
Trusted
)
// Excluded is a tool Mount refused and why, so the daemon can report it.
type Excluded struct {
Name string `json:"name"`
Reason string `json:"reason"`
}
// ServerConfig is one server to mount (aecd.json: Config.MCP[i]). Transport
// is "command" (Argv, a subprocess over stdio), "socket" (Socket, a Unix
// socket with the stdio framing) or "http" (URL, Streamable HTTP; TokenEnv
// names the variable holding a bearer token, never the token). Trust is
// "trusted" or "" (untrusted). Name is the prefix of every mounted tool. A
// command server never inherits the daemon's environment: it gets PATH (the
// daemon's absolute elements outside the state directory), HOME, USER, LANG,
// the POSIX LC_ names and TMPDIR, plus the variables PassEnv names, copied
// from the daemon's environment by name (a server's own token stays out of
// aecd.json, as token_env keeps a client's).
type ServerConfig struct {
Name string `json:"name"`
Transport string `json:"transport"`
Argv []string `json:"argv,omitempty"`
PassEnv []string `json:"pass_env,omitempty"`
Socket string `json:"socket,omitempty"`
URL string `json:"url,omitempty"`
TokenEnv string `json:"token_env,omitempty"`
Trust string `json:"trust,omitempty"`
Origin string `json:"origin,omitempty"`
}
// ServeConfig is what this daemon's own server exposes (Config.MCPServe).
// Workspace is the file tools' root (default Dir/mcp-workspace); AllowWrite
// lists write_file and execute_code; Commands are D4's command-backed
// tools. The Streamable HTTP form (aecd mcp -http) is a TCP listener with
// no peer uid, so it needs what the socket gets for free: TokenEnv names
// the variable holding the bearer token every request must carry (the
// listener refuses to start without it), Hosts is the Host allowlist
// (default 127.0.0.1, localhost and [::1] with any port) and Origins the
// Origin allowlist (an absent Origin is accepted).
type ServeConfig struct {
Workspace string `json:"workspace,omitempty"`
AllowWrite bool `json:"allow_write,omitempty"`
Commands []CommandTool `json:"commands,omitempty"`
TokenEnv string `json:"token_env,omitempty"`
Hosts []string `json:"hosts,omitempty"`
Origins []string `json:"origins,omitempty"`
// Idle is the longest a connection to Dir/mcp.sock may be silent before
// the daemon closes it (chapter 48), a duration as text; "" is 5m and
// "0" is no deadline.
Idle string `json:"idle,omitempty"`
}
// CommandTool is a tool backed by a command (D4 (ii)). The JSON arguments
// object is the command's stdin, each string, number or boolean argument
// the Schema declares as a top-level property (by exact name, which must be
// an identifier and distinct from the others once upper-cased) is exported
// as ARG_<NAME>, stdout is the text content, and a non-zero exit is an
// isError result carrying stderr. Schema is the tool's inputSchema; Timeout a duration string
// (default 30s). Argv is configuration the principal wrote; the arguments
// are the model's, and ServerTool says how the two are kept apart.
type CommandTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Argv []string `json:"argv"`
Schema json.RawMessage `json:"schema"`
Timeout string `json:"timeout,omitempty"`
}
Open mounts after the sandbox is configured and before the scheduler reads the tools’ names (openMCP), and the mounted tools enter tools() after chapter 43’s tools and before ToolHook, daemon-wide: a mount needs no workspace. The trial record of the captured turn below lists the order: read_file,write_file,search_files,terminal,scratch_write,scratch_read,book__greet,book__read_file,book__search_files.
// openMCP is chapter 44's part of Open: every server Config.MCP names is
// started or dialled, discovered and mounted, and the daemon's own server is
// built from Config.MCPServe, before the scheduler reads the tools' names.
// Two kinds of failure are told apart (Kyle, 2026-10-13, ruling 7e-E1b,
// which reverses 7e-E1: "a warning and continue to run, as that mimics the
// behavior of most harnesses"). A configuration that is wrong in itself
// fails Open. Before any server is started: a name (a prefix that ends in an
// underscore among them), trust or transport the rules refuse, a duplicate
// prefix, a command server with no argv, a pass_env naming PATH, a relative
// program, a URL that carries a secret or would send a token in the clear.
// Found while mounting (the servers already started are closed): a program
// that lies inside the state directory. checkToolNames then checks once more,
// over the whole set, an invariant no mount can break (mcp.Mount excludes a
// second tool of one name and the prefix rules keep two servers from making
// one). A server that is well
// configured and cannot be started, dialled, discovered or listed (the
// program is not installed, the socket is not there, the server answers with
// an error or not within mountTimeout) is warned of once with its name and
// the reason, cleaned as every text a server controls is; its tools are
// absent; MountReport and daemon/status show it as down with the reason; and
// the daemon runs. It is not retried: the next start is the retry.
func (d *Daemon) openMCP(ctx context.Context) (err error) {
defer func() {
if err != nil {
d.closeMounts()
}
}()
seen := map[string]bool{}
for _, cfg := range d.cfg.MCP {
if seen[cfg.Name] {
return fmt.Errorf("daemon: mcp: two servers are named %q", cfg.Name)
}
seen[cfg.Name] = true
if _, err := checkMountConfig(cfg); err != nil {
return fmt.Errorf("daemon: mcp %q: %w", cfg.Name, err)
}
}
for _, cfg := range d.cfg.MCP {
m, err := d.mountOne(ctx, cfg)
if err != nil {
var ce *mountConfigError
if errors.As(err, &ce) {
return fmt.Errorf("daemon: mcp %q: %w", cfg.Name, err)
}
reason := mcp.Clean(err.Error(), 300)
d.warnf("daemon: mcp %q: not mounted: %s; its tools are absent and it is not retried until the daemon is restarted", cfg.Name, reason)
d.mounts = append(d.mounts, &mount{cfg: cfg, report: MountReport{Server: cfg.Name, Tools: []string{}, Down: "not mounted at start (not retried): " + reason}})
continue
}
d.mounts = append(d.mounts, m)
d.mounted = append(d.mounted, m.tools...)
}
if err := d.checkToolNames(); err != nil {
return err
}
if d.mcpServer, err = d.buildMCPServer(); err != nil {
return fmt.Errorf("daemon: mcp_serve: %w", err)
}
return nil
}
// mountOne builds the transport the configuration names, discovers the
// server, mounts its tools and logs the outcome. A command server is a
// child of the daemon: argv[0] resolved once to an absolute path through
// the daemon's absolute PATH elements outside Dir (never a relative hit),
// the environment serverEnv (never the daemon's), its stderr the daemon's
// log, its own process group (stdio.Command), and never the sandbox's
// Runner: a Runner runs one command to completion over a byte string, and
// an MCP server is a long-lived two-way stream. It is configuration the
// principal wrote, and chapter 48 is where it is vetted.
func (d *Daemon) mountOne(ctx context.Context, cfg mcp.ServerConfig) (*mount, error) {
trust, err := checkMountConfig(cfg)
if err != nil {
return nil, err
}
m := &mount{cfg: cfg, report: MountReport{Server: cfg.Name, Tools: []string{}}}
var inner mcp.Transport // what Close and the client reach
var progPath string // a command server's resolved program (chapter 48's manifest and mount record)
var progEntry *audit.ProgramEntry
var progErr error
switch cfg.Transport {
case "command":
prog, err := mcp.ResolveProgram(cfg.Argv[0], d.hostPath(), d.cfg.Dir)
if err != nil {
// A program that is not there, or not executable, is a server that
// cannot be started (warn and continue); one that is there but
// inside the state directory, which the model can write, is a
// configuration the rule refuses.
if _, lerr := mcp.ResolveProgram(cfg.Argv[0], d.hostPath(), ""); lerr == nil {
return nil, &mountConfigError{err}
}
return nil, err
}
// The server's working directory is a directory of its own, not the
// state directory: whatever it writes by a relative path lands there,
// not beside the lock, the sockets and the journal. The name has a
// prefix, so that no server name (a "." or ".." passes the name
// rule) names the parent.
cwd := filepath.Join(d.cfg.Dir, "mcp-cwd", "s-"+cfg.Name)
if err := os.MkdirAll(cwd, 0o700); err != nil {
return nil, err
}
cmd := exec.Command(prog, cfg.Argv[1:]...)
cmd.Dir = cwd
cmd.Env = d.serverEnv(cfg)
// stdio.Command sets the parent-death signal with the forking thread pinned (chapter 48): a daemon that dies by SIGKILL takes its command servers with it; a descendant of a server is outside the signal, and a setsid one outside the group kill too, which stays a stated limit.
progPath = prog
if trust == mcp.Trusted || d.vetOut != nil {
// Hashed before the program is started: a swap between the exec
// and a later hash would go unseen.
progEntry, progErr = audit.Program(prog, cfg.PassEnv)
}
m.cmd = &stdio.Command{Cmd: cmd, Stderr: &serverLog{d: d, name: cfg.Name}}
if err := m.cmd.Start(ctx); err != nil {
return nil, err
}
inner = m.cmd
case "socket":
s := &stdio.Socket{Path: cfg.Socket, Log: &serverLog{d: d, name: cfg.Name}}
if err := s.Dial(ctx); err != nil {
return nil, err
}
inner = s
case "http":
hc := &streamable.Client{URL: cfg.URL, TokenEnv: cfg.TokenEnv, Origin: cfg.Origin}
if tok, ok := d.Token(cfg.TokenEnv); ok { // chapter 48: the broker's value, read once at Open
hc.Token = tok
}
inner = hc
}
m.tr = inner
if cfg.Transport != "http" { // an HTTP server has no connection to lose: each call is its own request
m.watch = &watched{Transport: inner, d: d, name: cfg.Name}
m.tr = m.watch
m.watch.setMounting(true)
}
dctx, cancel := context.WithTimeout(ctx, mountTimeout)
defer cancel()
client := &mcp.Client{T: m.tr, Info: mcp.Info{Name: "aecd", Version: mcpVersion}}
disc, err := client.Discover(dctx)
if err != nil {
m.abandon()
return nil, err
}
d.logf("mcp: %s: %s", cfg.Name, mcp.Describe(disc))
if disc.Instructions != "" {
// A server's instructions are untrusted text: logged, cut, and shown
// to no model (the only text of a server the model reads is each
// mounted tool's description, as its tool spec).
d.logf("mcp: %s: instructions (not given to the model): %s", cfg.Name, cut(disc.Instructions, 200))
}
tools, excluded, err := mcp.Mount(dctx, client, cfg.Name, trust)
if err != nil {
m.abandon()
return nil, err
}
// Chapter 48, the rug-pull rule (D-k3): a server configured trusted is
// trusted only against Dir/mcp.lock, the manifest aecd vet mcp -write
// stored when the principal looked at it. No lock, no entry, or tools that
// differ from the entry, and it is mounted untrusted (every call marked)
// with one warning that says why. Vetting itself reads the manifest and
// consults nothing.
lockState := ""
if trust == mcp.Trusted || d.vetOut != nil {
// The manifest is of the tools Mount returned (the ones the model is
// given), not of a second tools/list, and of the program as hashed
// before it was started.
merr := progErr
var cur audit.MCPManifest
if merr == nil {
defs := make([]mcp.Tool, 0, len(tools))
for _, t := range tools {
if mt, ok := t.(*mcp.Mounted); ok {
defs = append(defs, mt.Tool)
}
}
cur, merr = audit.MCPFrom(disc.ServerInfo, disc.SupportedVersions, defs, cfg.Name, progEntry)
}
if d.vetOut != nil {
if merr != nil {
m.abandon()
return nil, merr
}
d.vetOut[cfg.Name] = cur
for _, t := range tools {
if mt, ok := t.(*mcp.Mounted); ok {
d.vetTools[cfg.Name] = append(d.vetTools[cfg.Name], VetTool{Name: mt.Tool.Name, Description: mcp.Clean(mt.Tool.Description, 400)})
}
}
} else {
why := ""
lock, lerr := audit.ReadMCPLock(filepath.Join(d.cfg.Dir, "mcp.lock"))
entry, found := lock.Servers[cfg.Name]
switch {
case merr != nil:
why, lockState = "its manifest could not be read ("+mcp.Clean(merr.Error(), 200)+")", "drifted"
case errors.Is(lerr, audit.ErrNoLock):
why, lockState = "Dir/mcp.lock does not exist", "missing"
case lerr != nil:
why, lockState = "mcp.lock could not be read ("+mcp.Clean(lerr.Error(), 200)+")", "missing"
case !found:
why, lockState = "it has no entry in mcp.lock", "no_entry"
default:
lockState = "matched"
if diff := entry.Diff(cur); len(diff) > 0 {
why, lockState = "its tools differ from mcp.lock: "+mcp.Clean(strings.Join(diff, "; "), 600), "drifted"
}
}
if why != "" {
trust = mcp.Untrusted
if tools, excluded, err = mcp.Mount(dctx, client, cfg.Name, trust); err != nil {
m.abandon()
return nil, err
}
d.warnf("daemon: mcp %q is configured trusted but %s; mounted untrusted (aecd vet mcp -write records what you vetted)", cfg.Name, why)
}
}
}
if m.watch != nil {
m.watch.setMounting(false)
}
for _, e := range excluded {
d.logf("mcp: %s: excluded %s: %s", cfg.Name, e.Name, e.Reason)
}
for _, t := range tools {
m.report.Tools = append(m.report.Tools, t.Spec().Name)
}
m.report.Excluded = excluded
m.tools = tools
d.logf("mcp: %s: mounted %d tools", cfg.Name, len(tools))
if m.cmd != nil {
// A command server is not run through the sandbox (above): say so,
// once for each, as ruling 7e-E1 (2) required.
d.warnf("daemon: mcp %q: this command server runs on this host with the daemon's reach, outside any sandbox; an allowlisted environment and a process group of its own are its only containment", cfg.Name)
}
if d.audit != nil { // chapter 48: what was mounted, with what trust, over what reach
names := append([]string(nil), m.report.Tools...)
sort.Strings(names)
attrs := map[string]string{"trust": "untrusted", "transport": cfg.Transport, "tools": strconv.Itoa(len(names))}
if trust == mcp.Trusted {
attrs["trust"] = "trusted"
}
if lockState != "" {
attrs["lock"] = lockState
}
if progPath != "" {
attrs["program"] = progPath
if len(cfg.PassEnv) > 0 {
attrs["pass_env"] = strings.Join(cfg.PassEnv, ",")
}
}
d.record(audit.Record{Kind: "mount", Actor: "daemon", Subject: cfg.Name, Hash: sha256hex(strings.Join(names, "\n")), Attrs: attrs})
}
return m, nil
}
// mountConfigError marks a mountOne failure that is the configuration's
// fault and not the server's: Open refuses it (see openMCP).
type mountConfigError struct{ err error }
func (e *mountConfigError) Error() string { return e.err.Error() }
func (e *mountConfigError) Unwrap() error { return e.err }
// checkMountConfig is every check of one Config.MCP entry that needs neither
// a process nor a connection: what is wrong with the entry itself. It
// returns the entry's trust. Each failure is a *mountConfigError.
func checkMountConfig(cfg mcp.ServerConfig) (mcp.Trust, error) {
bad := func(format string, args ...any) (mcp.Trust, error) {
return mcp.Untrusted, &mountConfigError{fmt.Errorf(format, args...)}
}
if !mcp.ToolNamePattern.MatchString(cfg.Name) || strings.Contains(cfg.Name, "__") || strings.HasSuffix(cfg.Name, "_") {
return bad("the name is the mounted tools' prefix: 1-128 characters of [A-Za-z0-9_.-] without a double underscore and not ending in an underscore")
}
trust := mcp.Untrusted
switch cfg.Trust {
case "", "untrusted":
case "trusted":
trust = mcp.Trusted
default:
return bad("trust must be \"trusted\" or absent, not %q", cfg.Trust)
}
switch cfg.Transport {
case "command":
if len(cfg.Argv) == 0 {
return bad("a command server needs argv")
}
for _, k := range cfg.PassEnv {
if k == "PATH" {
return bad(`pass_env names PATH, which the daemon sets itself (the absolute elements outside the state directory); a server cannot be given the daemon's PATH`)
}
}
if p := cfg.Argv[0]; strings.ContainsRune(p, filepath.Separator) && !filepath.IsAbs(p) {
return bad("mcp: %q is a relative path; a program is named by an absolute path or a bare name looked up in PATH", p)
}
case "socket":
case "http":
if err := streamable.CheckURL(cfg.URL); err != nil { // no credentials, query or fragment; the error repeats no URL
return bad("%v", err)
}
u, err := url.Parse(cfg.URL)
if err != nil {
return bad("url: %v", err)
}
host := u.Hostname()
if u.Scheme != "https" && !(u.Scheme == "http" && (host == "127.0.0.1" || host == "localhost" || host == "::1")) {
return bad("url %q: a bearer token over cleartext leaves the host; use https://, or http:// to 127.0.0.1 or localhost", cfg.URL)
}
default:
return bad("transport must be command, socket or http, not %q", cfg.Transport)
}
return trust, nil
}
// abandon closes what a mount that failed after its transport was built had
// opened, and relays the last of a command server's stderr, which is often
// the reason it failed.
func (m *mount) abandon() {
if m.tr != nil {
m.tr.Close()
}
if m.cmd != nil {
if sl, ok := m.cmd.Stderr.(*serverLog); ok {
sl.Flush()
}
}
}
// checkToolNames refuses a tool set with two tools of one name: a mounted
// name is prefix__name and a prefix holds no double underscore, so it can
// never equal one of the daemon's own names or a job's default (chapter 42's
// filter is by name), and two servers cannot share a prefix; this is the
// check that says so at Open, over the same set checkJobTools reads.
func (d *Daemon) checkToolNames() error {
seen := map[string]bool{}
for _, t := range d.tools(filepath.Join(d.cfg.Dir, "jobs-tools-check")) {
n := t.Spec().Name
if seen[n] {
return fmt.Errorf("daemon: two tools are named %q", n)
}
seen[n] = true
}
return nil
}
// closeMounts closes every transport (a command server: stdin closed, the
// grace, then SIGKILL to its process group, then Wait) and logs a server
// that had to be killed.
func (d *Daemon) closeMounts() error {
var first error
for _, m := range d.mounts {
if m.tr == nil {
continue
}
if err := m.tr.Close(); err != nil && first == nil {
first = err
}
if m.cmd != nil && m.cmd.Killed() {
d.logf("mcp: %s: killed after grace", m.cfg.Name)
}
if m.cmd != nil {
if sl, ok := m.cmd.Stderr.(*serverLog); ok {
sl.Flush()
}
}
}
d.mounts, d.mounted = nil, nil
return first
}
// MountReport is what the mounts yielded, for daemon/status.
func (d *Daemon) MountReport() []MountReport {
var out []MountReport
for _, m := range d.mounts {
r := m.report
if m.watch != nil {
r.Down = m.watch.reason()
}
out = append(out, r)
}
return out
}
func cut(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
A mount that cannot be made is warned of, and the daemon runs. Two kinds of failure are told apart, and openMCP checks the first over every entry before it starts any server (checkMountConfig). An entry that is wrong in itself fails Open with the server’s name and releases the directory lock: a name that is not 1 to 128 characters of [A-Za-z0-9_.-] without a double underscore and not ending in an underscore, a trust that is neither trusted nor absent, a transport that is not command, socket or http, a command server with no argv, a pass_env that names PATH, a relative program path, an http URL that carries credentials, a query or a fragment or would send a token over cleartext to a host that is not loopback, and two servers of one name. One more refusal is found only while mounting, with the servers already started closed: a program that lies inside the state directory, which mountOne finds when it resolves the program. After the mounts checkToolNames (below) checks the whole set once more for two tools of one final name, which no mount can now make. A server that is well configured and cannot be started, dialled, discovered or listed is a failure of the world and not of the entry: a program that is not installed, a socket nobody serves, a legacy server, a server that does not answer server/discover within mountTimeout (30 s), a listing over the bounds. openMCP warns once, whatever -v says, with the server’s name and the reason, which went through mcp.Clean as every text a server controls does (daemon: mcp "old": not mounted: …; its tools are absent and it is not retried until the daemon is restarted). The server keeps an entry in MountReport with no tools and Down set to not mounted at start (not retried): and the same reason, which aecd status prints as mcp: old: 0 tools, down: …. The other servers mount, and the daemon opens. It is not retried, for the reason a server that stops after it is mounted is not restarted: a retry is a policy about what state the server held and whether a call may be repeated, and the next start is the retry.
The rule has costs. The daemon runs with fewer tools than its configuration names, so a turn that wanted fx__echo has none, and the model’s call to it is answered with toolcall’s ordinary observation, no tool named fx__echo. checkJobTools cannot check a job’s tools list against tools that were never listed, so it accepts a name spelt as a down mount’s prefix, a double underscore and anything after it; the job’s turn lacks the tool. It also accepts, with one warning through Config.Warn that names the job, the tool and the server (aecd: job "j": tool "fx__nope" is not among the tools mounted from MCP server "fx"; the job runs without it), once for each name a job lists, a name spelt as an up mount’s prefix that is not among the tools the server mounted (it did not list it, or mcp.Mount excluded it): the server may have changed since the reader wrote the job, and the daemon runs with fewer tools than the configuration names, as for a down mount. Every part of that warning is the reader’s (the job and tool names are in aecd.json, and the server’s name is its configured one), so none of it passes mcp.Clean. A name that begins with no configured mount’s prefix is still refused, whichever mounts are up. The default job filter is six fixed names, none of which a mount can take (a mounted name holds a double underscore), and the down mount does not change it. No collision between two servers’ tools depends on which servers are up: a prefix holds no double underscore and does not end in an underscore, so the first double underscore of a final name ends its prefix, and two prefixes cannot make one name (prefix__name, with a and a_ and the tools _b and b, would have made a___b twice, which is why a prefix that ends in an underscore is refused). And Open waits up to mountTimeout, and two seconds more to stop a command server, for each server that hangs, one after the other. The first build refused, by the reasoning that holds for an embedder that is not loaded and a sandbox lever the host lacks (chapter 43): a daemon that runs with less than its configuration names is not the one the reader described. The reader preferred the other behaviour, a warning and a daemon that runs, which is what most harnesses do. The embedder and the sandbox still refuse, because a daemon without either is not the daemon the configuration describes; a mount is one tool source among several. TestMountConfigErrorFailsOpen (with a good server ahead of the bad entry, which is not mounted either), TestMountFailureWarnsAndContinues (a legacy server, a dead socket, a missing program, a command server that exits at once, a socket that answers with what is not JSON-RPC, one whose reply is over the line bound and one whose error carries control and bidi characters, each beside a good server whose tools are served, each warned of once with the stream’s own cause and no control character in the warning or the status, with a clean close and a second Open), TestMountTimeoutBoundsOpen (a server that accepts and never answers), TestFailedMountLeavesNothingBehind (a command server that hangs has no process left, found by its pid, and a socket stand-in sees its connection end), TestMountDuplicateFinalNames (the a and a_ pair is refused with both servers up and with one down), TestMountDownToolIsUnknownToTurnsAndJobs, TestJobNamingAnUnlistedToolOfAnUpServerWarnsAndRuns (one warning, and the job’s tool set keeps its other named tools) and TestJobNamingAnUnknownToolOfNoMountStillRefusesOpen pin the rule.
Names. A mounted tool is prefix__name. A prefix holds no __, no tool of the daemon’s own has __ in its name, two servers may not share a prefix and a prefix does not end in an underscore, so a + _b and a_ + b cannot both make a___b; checkToolNames checks the whole set once more. Chapter 42’s job tool filter is by name, so the consequence is that no server can take the name of a default job tool, and a job reaches a mounted tool only by naming it in its tools list; TestMountedNamesNeverCollide checks the default job set for any name with a __ and the named case end to end.
A command server is a child process, and chapter 43’s lessons apply to it. Its program is resolved once, at configuration, to an absolute path through the daemon’s own absolute PATH elements outside the state directory (mcp.ResolveProgram), never a relative hit, and a program that lies inside the working directory, by name or through a link, is refused at Open (a relative path with a separator is too; a bare name found nowhere on that PATH is a server that cannot be started, and is warned of as above). Its environment is not the daemon’s. It is a list, shown below: PATH (those same elements) and an allowlist of names, plus the variables pass_env names, copied by name, which is how a server’s own token stays out of aecd.json; pass_env may not name PATH. TestMountEnvAllowlist plants a sentinel variable in the daemon’s environment and asks the child for its presence only. The server’s working directory is a directory of its own, Dir/mcp-cwd/s-NAME, and not the state directory, so a relative write lands there and not beside the lock. It runs in its own process group, and Close is stdin closed, a grace, then SIGKILL to the group, logged when it was needed (TestMountCloseLogsKill). Its stderr reaches the log line by line and nowhere else, under two bounds: a line is cut at 4 KiB and at most 64 KiB is relayed per minute; past that the daemon keeps reading, so the server never blocks on a full pipe, counts what it drops, and says how much in one line at the window’s end (TestStderrRelayIsBounded, TestStderrRelayAccounting).
The environment is built by two small functions, and the allowlist is a variable:
// serverEnvNames are the daemon's variables a command server inherits beside
// PATH: chapter 27's allowlist for a shell (the POSIX locale names, never a
// prefix). A server's own token is named in pass_env, never pasted into
// aecd.json.
var serverEnvNames = []string{"HOME", "USER", "LANG", "LC_ALL", "LC_CTYPE", "LC_COLLATE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "TMPDIR"}
// hostPath is the daemon's PATH reduced to its absolute elements outside the
// state directory (tool.PathOutside): what a server's argv[0] is resolved
// through and what the server gets as PATH.
func (d *Daemon) hostPath() string {
p := tool.PathOutside(os.Getenv("PATH"), d.cfg.Dir)
if p == "" {
p = tool.DefaultSandboxPath
}
return p
}
// serverEnv is the whole environment a command server gets: never
// os.Environ(); PATH by hostPath, the allowlisted names when set, and the
// names cfg.PassEnv lists when set.
func (d *Daemon) serverEnv(cfg mcp.ServerConfig) []string {
env := []string{"PATH=" + d.hostPath()}
for _, k := range append(append([]string(nil), serverEnvNames...), cfg.PassEnv...) {
if v, ok := os.LookupEnv(k); ok {
env = append(env, k+"="+v)
}
}
return env
}
It is not run through the sandbox. The backend of chapter 43 runs one command to completion over a byte string, and an MCP server is a long-lived two-way stream; no backend has a streaming method, and adding one is a change to chapter 43 this chapter did not make. So a mounted command server has the daemon’s reach on the host, with an allowlisted environment and a process group as its only containment, and the daemon says so once for each such server at Open, through Config.Warn. The capture’s log below holds that line and, before it, a different warning: the child’s own, about its own command tools. The first version of this code said nothing, which left the condition on which the unsandboxed server was accepted unmet; TestMountedCommandServerIsWarnedOf asserts the line for a command mount and its absence for a socket mount and an HTTP mount.
A server that dies is noticed by the next call that fails, and not restarted. The transport a command or socket mount’s client calls through is a watched wrapper. It notices a call that fails for a reason other than its own context ending: the server’s process exited, its connection closed, or the stream failed on a write that outlived its context by more than a second, which is a server that stopped reading. Nothing polls, so a server that exits while idle is noticed by the next call, not before. The call that gives up on a stuck write returns its own context’s error and says nothing of the server; the next call, under a live context, finds the stream failed. The line a call returns is mcp server "X" has stopped inside the tool’s fence; the daemon’s Config.Warn says it once (not once per concurrent call), as daemon: mcp "X": the server stopped (...); its tools fail until the daemon is restarted; daemon/status and aecd status show the mount as down; and every later call answers at once. The wrapper does not count a context error as the server’s death, which is the other half of the cancelled-call fix above (TestEndedContextDoesNotStopAMount).
Nothing restarts the server, and that declines a SHOULD of the stdio page (Unexpected Termination): “If the server process exits unexpectedly, the client SHOULD restart it. Because the protocol is stateless, any in-flight requests are simply lost and the client can retry them against the fresh process.” The page’s argument covers the protocol. A retried tools/call is still a repeated side effect unless the tool is idempotent, this daemon does not decide that for a server, and a restart policy is not built (chapter 48 vets what a server offers, not whether to restart it). The cost is a mount that stays down, with the daemon saying so, until the daemon is restarted. An HTTP mount has no connection to lose, so it is not wrapped. The mount’s URL goes through streamable.CheckURL at configuration, and a cleartext http:// URL to a host other than 127.0.0.1, localhost or ::1 is refused whether or not a token is configured.
The command-backed tool, and the working directory that is not the workspace
The daemon’s server offers, besides the file tools, tools the principal writes as commands. A CommandTool is a name, a description, an argv and a schema. The contract: the model’s arguments are validated against the schema first and the command never runs on a failure (invalid arguments); then the command gets the arguments twice, as a JSON object on standard input and as ARG_<NAME> environment variables; its standard output is the text content; a non-zero status is an isError result carrying standard error.
// identifier is the argument names exported as ARG_<NAME>.
var identifier = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
// MaxArgEnvBytes bounds one ARG_ value. Linux caps a single environment
// string at 128 KiB (MAX_ARG_STRLEN) and the whole argument and environment
// block at a quarter of the stack limit (about 2 MiB); 32 KiB leaves room
// for several arguments, and a larger value is on stdin anyway. A call with
// an exported argument over it, or holding a NUL byte (which an environment
// string cannot), fails with an isError result naming the argument, never
// with the operating system's E2BIG (whose text names the script's path).
const MaxArgEnvBytes = 32 << 10
// ResolveProgram is chapter 43's rule for a program the daemon itself
// starts, applied to the two it starts for this chapter (a command server's
// argv[0] and an unsandboxed command tool's): an absolute path is checked to
// be an executable regular file; a relative path with a separator in it is
// refused (it would name the working directory, which a model can write);
// a bare name is looked up in path, which the caller has already reduced to
// absolute elements outside the workspace (tool.PathOutside), so a hit can
// never be a relative one (exec.ErrDot). Whichever way the name was found,
// the program with its symbolic links resolved must lie outside dir (the
// working directory the child gets and a model may write): an absolute path
// inside it, a link inside it, and a link anywhere that points into it are
// refused, because a model that can replace the file chooses what runs. The
// result is the absolute path as named, not the link's target (a program may
// dispatch on its own name), resolved once at configuration and never again
// at call time. dir "" skips the containment check.
func ResolveProgram(name, path, dir string) (string, error) {
var prog string
if strings.ContainsRune(name, filepath.Separator) {
if !filepath.IsAbs(name) {
return "", fmt.Errorf("mcp: %q is a relative path; a program is named by an absolute path or a bare name looked up in PATH", name)
}
if err := executable(name); err != nil {
return "", err
}
prog = name
} else {
for _, d := range filepath.SplitList(path) {
if !filepath.IsAbs(d) {
continue // never a relative element, whatever the caller passed
}
p := filepath.Join(d, name)
if err := executable(p); err == nil {
prog = p
break
}
}
if prog == "" {
return "", fmt.Errorf("mcp: %q is not an executable on the daemon's absolute PATH elements outside the state directory: %w", name, exec.ErrNotFound)
}
}
if dir != "" && programInside(prog, dir) {
return "", fmt.Errorf("mcp: %s is inside the working directory %s, which the model can write; a program is outside it", prog, dir)
}
return prog, nil
}
// programInside reports whether prog, lexically or after resolving every
// link in it, lies in dir (resolved the same way). A path that cannot be
// resolved counts as inside: the check fails closed.
func programInside(prog, dir string) bool {
within := func(p, d string) bool {
rel, err := filepath.Rel(d, p)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
if within(filepath.Clean(prog), filepath.Clean(dir)) {
return true
}
rp, err1 := filepath.EvalSymlinks(prog)
rd, err2 := filepath.EvalSymlinks(dir)
if err1 != nil || err2 != nil {
return true
}
return within(rp, rd)
}
// pathInside reports whether the absolute path p is dir or lies inside it,
// lexically or through links: the longest existing prefix of p is resolved and
// the rest appended, so a path that does not exist yet, under a link into dir,
// counts. Unlike programInside it does not fail closed on a path that does not
// exist, because an argument need not name a file; the daemon creates both
// directories before it asks.
func pathInside(p, dir string) bool {
within := func(p, d string) bool {
rel, err := filepath.Rel(d, p)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
p, dir = filepath.Clean(p), filepath.Clean(dir)
if within(p, dir) {
return true
}
rd, err := filepath.EvalSymlinks(dir)
if err != nil {
rd = dir // a directory that does not exist has no link to resolve
}
rest := ""
for q := p; ; q = filepath.Dir(q) {
if rq, err := filepath.EvalSymlinks(q); err == nil {
return within(filepath.Join(rq, rest), rd)
}
if q == filepath.Dir(q) {
return false
}
rest = filepath.Join(filepath.Base(q), rest)
}
}
func executable(p string) error {
fi, err := os.Stat(p)
if err != nil {
return err
}
if !fi.Mode().IsRegular() || fi.Mode().Perm()&0o111 == 0 {
return fmt.Errorf("mcp: %s is not an executable regular file", p)
}
return nil
}
// commandEnv is the environment a command tool's process gets, in both
// modes: what execute_code gives model-written code (sandbox.baseEnv, chapter
// 43) and nothing of the daemon's: a PATH with no element inside the
// workspace (path, or the FHS default when empty), HOME the workspace, a
// locale, a temporary directory and a dumb terminal.
func commandEnv(dir, path string) map[string]string {
path = tool.PathOutside(path, dir)
if path == "" {
path = tool.DefaultSandboxPath
}
return map[string]string{"PATH": path, "HOME": dir, "LANG": "C.UTF-8", "TMPDIR": "/tmp", "TERM": "dumb"}
}
// ServerTool turns a command-backed definition into an exposed tool, through
// a backend only (run set); with no backend it is refused, because it has no
// command directory to run in: see ServerToolIn, which takes one. The
// command is configuration the principal wrote; its arguments are the
// model's. With run set (chapter 43's backend, as the daemon configures it)
// the command runs through it exactly as execute_code's interpreter does:
// Argv as configured, the environment commandEnv(dir, path) plus the ARG_
// variables, the backend resolving argv[0] through that PATH. With run nil
// the command is a plain child of this process (the unsandboxed case, which
// the daemon warns about at Open): argv[0] is resolved once here through
// ResolveProgram over path, the child gets the same environment and nothing
// inherited, runs in its own process group, is killed with that group at the
// wall clock, and each output stream is kept to 64 KiB, the cut stated in
// the result. In both modes stdin is the validated arguments as JSON (decoded and encoded again, so a key the client repeated appears once, with the value that was validated), stdout is the text
// content, and a non-zero status is an isError result carrying stderr.
// Arguments are validated against Schema before anything runs. The
// ARG_<NAME> variables are the validated arguments and no others: exactly
// the schema's declared top-level properties, by exact name (so a key the
// schema does not declare, or one that differs only in case, sets nothing),
// when the value is a string, number or boolean. A declared name that is not
// an identifier, or two that are the same after upper-casing, is refused
// here, at configuration, because either would let one value stand for
// another.
func (c CommandTool) ServerTool(run tool.Runner, dir, path string) (ServerTool, error) {
return c.ServerToolIn(run, dir, "", path)
}
// ServerToolIn is ServerTool with the daemon's command directory named. dir is
// the workspace, which a client of the server may write (write_file). With
// run set the command runs in dir, confined by the backend, as execute_code's
// interpreter does. With run nil nothing confines the code, so the command
// never runs in dir or with dir as HOME: it runs in cmdDir, a directory of
// the daemon's own that the server's file tools cannot name, so a relative
// argument (an interpreter's script, a module, a rc file) resolves to
// something the principal put there and never to something a client wrote;
// cmdDir "" with run nil is refused, as is a cmdDir inside dir. In both modes
// an argv element after the program that is an absolute path inside dir is
// refused: a client can write the file it names, now or later. With run nil a
// relative element that names a path and resolves, against cmdDir, to a path
// inside dir is refused too (the elements are read whole: a path inside a -c
// string is not seen).
func (c CommandTool) ServerToolIn(run tool.Runner, dir, cmdDir, path string) (ServerTool, error) {
if !ToolNamePattern.MatchString(c.Name) {
return ServerTool{}, fmt.Errorf("command tool %q: the name is not 1-128 characters of [A-Za-z0-9_.-]", c.Name)
}
if len(c.Argv) == 0 {
return ServerTool{}, fmt.Errorf("command tool %s: argv is empty", c.Name)
}
schema := c.Schema
if len(schema) == 0 {
schema = json.RawMessage(`{"type":"object","additionalProperties":false}`)
}
if reason := Check(Tool{Name: c.Name, InputSchema: schema}); reason != "" {
return ServerTool{}, fmt.Errorf("command tool %s: %s", c.Name, reason)
}
timeout := 30 * time.Second
if c.Timeout != "" {
d, err := time.ParseDuration(c.Timeout)
if err != nil || d <= 0 {
return ServerTool{}, fmt.Errorf("command tool %s: timeout %q", c.Name, c.Timeout)
}
timeout = d
}
exported, err := exportedArgs(schema)
if err != nil {
return ServerTool{}, fmt.Errorf("command tool %s: %w", c.Name, err)
}
for _, a := range c.Argv[1:] {
if dir != "" && filepath.IsAbs(a) && pathInside(a, dir) {
return ServerTool{}, fmt.Errorf("command tool %s: the argument %q is a path inside the workspace, which a client of the server can write; a script is named relative to the command directory or outside the workspace", c.Name, a)
}
}
wd, home := dir, dir
if run == nil {
if cmdDir == "" || !filepath.IsAbs(cmdDir) {
return ServerTool{}, fmt.Errorf("command tool %s: with no sandbox the command runs in a command directory of the daemon's own, and none was given", c.Name)
}
if dir != "" && pathInside(cmdDir, dir) {
return ServerTool{}, fmt.Errorf("command tool %s: the command directory is inside the workspace, where the server's file tools reach it", c.Name)
}
// A relative element that names a path (it holds a separator, or is
// "..") resolves against the command directory; one that leaves it
// for the workspace names a file the client can write. Only whole
// elements are read: a path inside a -c string is not seen.
for _, a := range c.Argv[1:] {
if dir != "" && !filepath.IsAbs(a) && (a == ".." || strings.ContainsRune(a, filepath.Separator)) && pathInside(filepath.Join(cmdDir, a), dir) {
return ServerTool{}, fmt.Errorf("command tool %s: the argument %q resolves to a path inside the workspace, which a client of the server can write; a script is named relative to the command directory without leaving it, or outside the workspace", c.Name, a)
}
}
wd, home = cmdDir, cmdDir
path = tool.PathOutside(path, dir)
}
base := commandEnv(home, path)
argv := append([]string(nil), c.Argv...)
if run == nil {
prog, err := ResolveProgram(argv[0], base["PATH"], dir)
if err != nil {
return ServerTool{}, fmt.Errorf("command tool %s: %w", c.Name, err)
}
argv[0] = prog
}
def := Tool{Name: c.Name, Description: c.Description, InputSchema: schema}
call := func(ctx context.Context, raw json.RawMessage) (CallToolResult, error) {
var args map[string]any
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&args); err != nil {
return failed("arguments must be an object: " + err.Error()), nil
}
if vs := jsonschema.Validate(schema, args); len(vs) > 0 {
msgs := make([]string, 0, len(vs))
for _, v := range vs {
msgs = append(msgs, v.String())
}
return failed("invalid arguments: " + strings.Join(msgs, "; ")), nil
}
env := map[string]string{}
for k, v := range base {
env[k] = v
}
for _, k := range exported {
s, ok := HeaderValue(args, []string{k})
if !ok {
continue
}
if strings.IndexByte(s, 0) >= 0 {
return failed("argument " + k + " holds a NUL byte, which an environment variable cannot; it is on stdin"), nil
}
if len(s) > MaxArgEnvBytes {
return failed(fmt.Sprintf("argument %s is %d bytes, over the %d (MaxArgEnvBytes) an ARG_ variable carries; it is on stdin", k, len(s), MaxArgEnvBytes)), nil
}
env["ARG_"+strings.ToUpper(k)] = s
}
// Stdin is the validated arguments, encoded again: the client's own
// bytes may repeat a key (the decoder keeps the last value, and a
// script whose parser keeps the first would read the one that was
// never validated).
var stdin bytes.Buffer
enc := json.NewEncoder(&stdin)
enc.SetEscapeHTML(false)
if err := enc.Encode(args); err != nil {
return failed("arguments cannot be encoded: " + err.Error()), nil
}
cmd := tool.Command{Argv: argv, Dir: wd, Stdin: bytes.TrimRight(stdin.Bytes(), "\n"), Env: env, Wall: timeout}
var out tool.Output
var err error
if run != nil {
out, err = run.Run(ctx, cmd)
} else {
out, err = plainRun(ctx, cmd)
}
if err != nil {
return failed(c.Name + ": " + err.Error()), nil
}
if out.Status != 0 {
return failed(fmt.Sprintf("%s exited with status %d: %s", c.Name, out.Status, strings.TrimSpace(string(out.Stderr)))), nil
}
text := string(out.Stdout)
if out.Truncated {
text += fmt.Sprintf("\n[output cut: this tool keeps %d bytes of each stream]", plainCap)
}
return CallToolResult{ResultType: ResultComplete, Content: []Content{TextContent(text)}}, nil
}
return ServerTool{Tool: def, Call: call}, nil
}
// exportedArgs is the names ARG_ variables are made from: the top-level
// properties the schema declares. Checked here, once: each is an
// identifier, and no two are the same upper-cased.
func exportedArgs(schema json.RawMessage) ([]string, error) {
var top map[string]json.RawMessage
if err := json.Unmarshal(schema, &top); err != nil {
return nil, fmt.Errorf("schema is not an object: %w", err)
}
var props map[string]json.RawMessage
if raw, ok := top["properties"]; ok {
if err := json.Unmarshal(raw, &props); err != nil {
return nil, fmt.Errorf("properties is not an object: %w", err)
}
}
names := make([]string, 0, len(props))
for k := range props {
names = append(names, k)
}
sort.Strings(names)
upper := map[string]string{}
for _, k := range names {
if !identifier.MatchString(k) {
return nil, fmt.Errorf("the property %q cannot be an ARG_ variable: a name is letters, digits and underscores, not starting with a digit", k)
}
u := strings.ToUpper(k)
if prev, dup := upper[u]; dup {
return nil, fmt.Errorf("the properties %q and %q are both ARG_%s", prev, k, u)
}
upper[u] = k
}
return names, nil
}
func failed(msg string) CallToolResult {
return CallToolResult{ResultType: ResultComplete, IsError: true, Content: []Content{TextContent(msg)}}
}
Left off the page: plainRun, the unsandboxed path (the child is its own process group, the wall clock kills the group, and WaitDelay closes the pipes a second later, so a grandchild holding one cannot keep Wait from returning: TestCommandWallClock, TestCommandKillReachesTheGroup, TestCommandExitZeroWithADescendantHoldingTheOutput), and capped, the writer that keeps each output stream to 64 KiB and counts the rest (TestCommandOutputCap).
The environment variables carry the validated arguments and no others, and that took a correction. The first version exported every identifier-shaped key of the arguments object. JSON Schema allows undeclared properties by default, so a call carrying name, NAME and Name to a tool whose schema constrained name set ARG_NAME three times, the winner decided by map order, so the script could read a value the schema had never seen. Now exportedArgs takes the schema’s declared top-level properties, by exact name; a declared name that is not an identifier, or two that are the same after upper-casing, is refused at configuration, because either would let one value stand for another; and only a string, number or boolean is exported. TestCommandArgsAreTheValidatedOnes makes the three-key call 200 times through a recording runner and ten times against real children, and requires ARG_NAME to be the validated value every time. Standard input is the validated map encoded again, so a key the client repeated appears once with the value that was validated, for a script whose parser would otherwise take a different occurrence than the validator did.
There are two modes. With a sandbox backend configured, the command runs through the backend exactly as execute_code’s interpreter does: Argv as configured, the environment commandEnv returns (PATH, HOME, LANG, TMPDIR, TERM) plus the ARG_ variables, the working directory the workspace. With no sandbox, it is a plain child: argv[0] resolved once through ResolveProgram, the same environment, its own process group killed with it at the wall clock (30 s by default), each output stream kept to 64 KiB with the cut stated in the result. The daemon warns once, at Open, through Config.Warn that its command tools run unsandboxed, and a mounting daemon relays the warning, which is the first line of the capture’s log.
The working directory is the part a later review found. The server’s workspace is the directory its file tools read and, under allow_write, write. A command tool’s argv is usually an interpreter and a script, ["sh", "greet.sh"], and a relative script resolves in the working directory. If that directory is the workspace, the client of the server can rewrite the script. The review did exactly that: with allow_write and no sandbox, write_file replaced tool.sh, the next call to the tool ran the client’s text, and a file appeared outside the workspace. The server withholds execute_code in precisely this configuration because it has no sandbox, and the pair of write_file and a command tool handed the holder of a token what that refusal denied. Refusing at configuration any argv element that names an existing file would not have been enough, since the client writes the file later. The rule that holds is wider: with no sandbox, a command tool never runs with the workspace as its working directory or its HOME. It runs in Dir/mcp-command, a directory of the daemon’s own, mode 0700, which no file tool of the server can name (an absolute path, .. and a link are all outside the workspace, and Open refuses a workspace that contains it). A relative script, module or rc file therefore resolves to what the principal put there, provided its name does not leave the command directory: with no sandbox, a relative element that holds a separator is joined to the command directory at configuration, and one that lands inside the workspace (../mcp-workspace/tool.sh, in the default layout, where the two directories are siblings) is refused (TestCommandToolRefusesRelativePathsThatLeaveTheCommandDirectory). The check reads whole elements; a path inside a -c string is not one, and no check of elements can see it. Under a sandbox the working directory stays the workspace, as for execute_code, because the backend confines the code. In both modes an argv element after the program that is an absolute path inside the workspace, through a link too and whether or not the file exists, is refused at configuration. TestServerCommandScriptIsNotTheClients replays the review’s three calls (the tool runs the principal’s script, the client’s file never runs, no marker anywhere), and TestServerFileToolsCannotNameTheCommandDirectory tries an absolute path, .., sub/../.., a directory link and a file link against read_file, write_file and search_files. The cost is a rule for the principal: a relative script lives in Dir/mcp-command or is named absolutely.
The daemon as a server, and who can reach it
The server is built at Open from mcp_serve, and it has two entry points to the one object: aecd serve listens on Dir/mcp.sock (mode 0600 inside the 0700 directory, chapter 40’s SO_PEERCRED check before a byte is read), and aecd mcp -config FILE is the standalone form over stdio, for a host that launches servers as subprocesses; it opens the state directory itself, takes its own lock, mounts nothing, and exits 3 when a running daemon already holds the directory (a second process cannot own the memory service of the first). With -http it also serves Streamable HTTP, on a loopback address only (a literal loopback IP, or a name every address of which is loopback, decided after resolution and checked again on what was bound), with the required bearer token named by mcp_serve.token_env, the Host allowlist, and four http.Server limits (10 s to read headers, 60 s to read a request, 120 s idle, 32 KiB of headers, and no write timeout, because a tool call answers after the tool has run). There is no option in this part for another address. aecd mcp ends at the end of its input or on SIGTERM or SIGINT, and with -http it serves until a signal.
// MCPServer is the daemon's own server, built at Open from Config.MCPServe
// (nil: none; Serve then opens no mcp.sock). It exposes read_file and
// search_files over the server's workspace (MCPServe.Workspace, default
// Dir/mcp-workspace), write_file and, with a sandbox backend, execute_code
// only under AllowWrite, memory_recall when the daemon has a memory
// service, and each command tool. The server cannot ask for approval, so a
// call whose tool is Marked and reports that it needs approval is refused
// (serverTool), execute_code excepted: what the server lists is what it is
// willing to run unasked, and AllowWrite is the one opt-in. A write_file
// call is therefore written inside the workspace and refused outside it.
func (d *Daemon) MCPServer() *mcp.Server { return d.mcpServer }
func (d *Daemon) buildMCPServer() (*mcp.Server, error) {
sc := d.cfg.MCPServe
if sc == nil {
return nil, nil
}
ws := sc.Workspace
if ws == "" {
ws = filepath.Join(d.cfg.Dir, "mcp-workspace")
}
ws, err := filepath.Abs(ws)
if err != nil {
return nil, err
}
if err := os.MkdirAll(ws, 0o700); err != nil {
return nil, err
}
srv := &mcp.Server{Info: mcp.Info{Name: "aecd", Version: mcpVersion}, TTLMs: 60000, Instructions: "Tools of one aecd daemon over its MCP workspace."}
// The PATH the command tools get: chapter 43's rule for code on this host
// (sandbox.HostPath: the daemon's absolute elements under a Local, the FHS
// constant under podman or ssh); with no sandbox the command runs on this
// host too, so it gets the same host PATH (a Nix host has no /bin/python3).
path := sandbox.HostPath(d.sandbox)
if d.sandbox == nil {
path = tool.PathOutside(os.Getenv("PATH"), "")
}
for _, t := range tool.FileTools(ws) {
if t.Spec().Name == "write_file" && !sc.AllowWrite {
continue
}
if t.Spec().Name == "write_file" {
t = &noHardLink{Tool: t, ws: ws} // chapter 48: a write onto a file with a second name replaces the other name's content too
}
srv.Tools = append(srv.Tools, withoutHostPath(serverTool(t), ws))
}
if sc.AllowWrite {
if d.sandbox != nil {
srv.Tools = append(srv.Tools, serverTool(&sandbox.ExecuteCode{Backend: d.sandbox, Workspace: ws, Limits: d.sandboxLimits(), Languages: sandbox.DefaultLanguages(), Path: path}))
} else {
d.logf("mcp_serve: execute_code is not exposed: no sandbox is configured")
}
}
if d.mem != nil {
for _, t := range d.mem.Tools(nil, "") {
if t.Spec().Name == "memory_recall" {
srv.Tools = append(srv.Tools, serverTool(t))
}
}
}
// With no sandbox the command tools run in a directory of the daemon's
// own, never in the workspace a client may write: the file tools cannot
// name it (the check below refuses a workspace that contains it).
cmdDir := ""
if len(sc.Commands) > 0 && d.Runner() == nil {
cmdDir, err = filepath.Abs(filepath.Join(d.cfg.Dir, "mcp-command"))
if err != nil {
return nil, err
}
if err := os.MkdirAll(cmdDir, 0o700); err != nil {
return nil, err
}
if err := os.Chmod(cmdDir, 0o700); err != nil {
return nil, err
}
}
for _, c := range sc.Commands {
st, err := c.ServerToolIn(d.Runner(), ws, cmdDir, path)
if err != nil {
return nil, err
}
srv.Tools = append(srv.Tools, st)
}
if len(sc.Commands) > 0 && d.Runner() == nil {
d.warnf("daemon: mcp_serve: %d command tool(s) run on this host unsandboxed (no \"sandbox\" is configured), with the model's arguments on stdin and in ARG_ variables", len(sc.Commands))
}
names := map[string]bool{}
for _, t := range srv.Tools {
if names[t.Tool.Name] {
return nil, fmt.Errorf("two tools are named %q", t.Tool.Name)
}
names[t.Tool.Name] = true
}
return srv, nil
}
// noHardLink refuses a write_file whose target is a regular file with more
// than one name (chapter 48): a hard link in the server's workspace to a
// file elsewhere (a command tool's script, a configuration file the
// principal linked in) would let a client replace the other name's content
// through a path the workspace check calls inside. It resolves the path as
// the tool does (the workspace joined with a relative path), looks at the
// file itself, and forwards the tool's own marking. The check is a look
// before the write: a link made between the look and the tool's open, by an
// actor with write access to the workspace (not the MCP client, which cannot
// make links), is not seen.
type noHardLink struct {
agent.Tool
ws string
}
func (t *noHardLink) Unwrap() agent.Tool { return t.Tool }
func (t *noHardLink) NeedsApproval(call toolcall.Call) (bool, string) {
if m, ok := t.Tool.(agent.Marked); ok {
return m.NeedsApproval(call)
}
return false, ""
}
func (t *noHardLink) Call(ctx context.Context, call toolcall.Call) agent.Result {
if p, _ := call.Arguments["path"].(string); p != "" {
target := p
if !filepath.IsAbs(target) {
target = filepath.Join(t.ws, target)
}
fi, err := os.Lstat(target)
if err == nil && fi.Mode()&os.ModeSymlink != 0 {
fi, err = os.Stat(target)
}
if err == nil && fi.Mode().IsRegular() {
if n := linkCount(fi); n > 1 {
return agent.ErrorResult("write_file: refused: the target has %d names (a hard link), and the other names cannot be seen", n)
}
}
}
return t.Tool.Call(ctx, call)
}
// withoutHostPath rewrites the host's absolute workspace path in an error a
// file tool returns ("lstat /srv/ws/notes.txt: no such file") to a path
// relative to the workspace: the client is told what failed, not where the
// workspace is on the host. Results that are not errors are the file's own
// bytes and are left as they are.
func withoutHostPath(st mcp.ServerTool, ws string) mcp.ServerTool {
inner := st.Call
st.Call = func(ctx context.Context, raw json.RawMessage) (mcp.CallToolResult, error) {
res, err := inner(ctx, raw)
if err != nil || !res.IsError {
return res, err
}
content := make([]mcp.Content, len(res.Content))
for i, c := range res.Content {
c.Text = strings.ReplaceAll(strings.ReplaceAll(c.Text, ws+string(filepath.Separator), ""), ws, ".")
content[i] = c
}
res.Content = content
return res, nil
}
return st
}
// serverTool exposes one agent.Tool: its spec is the definition, the
// arguments are validated against the spec (servers MUST validate every
// input) and decoded as toolcall.Decode would (UseNumber), the Result's text
// parts are text content, its image_url data URLs image content, and any
// kind but ok and empty is isError with the text.
//
// A tool's guard against a dangerous call lives in its NeedsApproval, which
// the agent loop consults before it calls the tool; this server calls the
// tool directly, so it consults NeedsApproval itself and refuses a call that
// needs approval: the server cannot ask, because the one who could is the
// principal at the other end of a socket or a token, and what the server
// lists is what it is willing to run unasked. write_file is marked when its
// path leaves the workspace, by its text or through a link, and so is
// refused there and written inside it. execute_code is the one stated
// exception: it is marked on every call, it is offered only under
// AllowWrite and a sandbox backend, and the backend is the guard.
func serverTool(t agent.Tool) mcp.ServerTool {
spec := t.Spec()
_, runsInSandbox := t.(*sandbox.ExecuteCode)
marked, isMarked := t.(agent.Marked)
params := spec.Parameters
if len(params) == 0 {
params = json.RawMessage(`{"type":"object"}`)
}
var n int64
var mu sync.Mutex
return mcp.ServerTool{Tool: mcp.Tool{Name: spec.Name, Description: spec.Description, InputSchema: params},
Call: func(ctx context.Context, raw json.RawMessage) (mcp.CallToolResult, error) {
args := map[string]any{}
if len(raw) > 0 {
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&args); err != nil {
return mcpError("arguments must be an object: " + err.Error()), nil
}
}
if vs := jsonschema.Validate(params, args); len(vs) > 0 {
msgs := make([]string, 0, len(vs))
for _, v := range vs {
msgs = append(msgs, v.String())
}
return mcpError("invalid arguments: " + strings.Join(msgs, "; ")), nil
}
hash, _ := toolcall.HashCall(spec.Name, args)
if isMarked && !runsInSandbox {
if need, _ := marked.NeedsApproval(toolcall.Call{Name: spec.Name, Arguments: args, Hash: hash}); need {
// The reason is not repeated: it names the path the tool
// resolved to, which is the host's business.
return mcpError(spec.Name + ": refused: this call needs approval, and this server cannot ask for it, so it was not run"), nil
}
}
mu.Lock()
n++
id := fmt.Sprintf("mcp-%d", n)
mu.Unlock()
res := t.Call(ctx, toolcall.Call{ID: id, Name: spec.Name, Arguments: args, Hash: hash})
return resultContent(res), nil
}}
}
Left off the page: mcpError and resultContent, which turn an agent.Result into the server’s CallToolResult (TestServerToolsValidateTheirArguments, TestServerToolRefusesWhatNeedsApproval); startMCPSocket and serveMCPListener, which listen on mcp.sock and run chapter 40’s SO_PEERCRED check before a byte is read (TestMCPSocket, TestMCPSocketStalePaths); and daemonUID, the uid the check expects, a variable so that a test can make the real check refuse the only uid a test host has (TestMCPSocketPeerCheck).
// httpLimits are the http.Server bounds of aecd mcp -http. The listener is
// on the loopback of one host and every client is a process of that host, so
// the numbers only have to stop a client that opens a connection and then
// does nothing from holding a goroutine and a descriptor for ever.
type httpLimits struct {
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
}
// defaultHTTPLimits: ReadHeaderTimeout 10 s (a loopback client sends its
// headers in microseconds; ten seconds tolerates a starved host and not a
// slowloris); ReadTimeout 60 s for the whole request, headers and body, the
// body being capped at 4 MiB by the handler; IdleTimeout 120 s between
// requests on a kept-alive connection; MaxHeaderBytes 32 KiB (the handler
// reads a dozen headers, and net/http's default is 1 MiB). There is no
// WriteTimeout: a tool call answers after the tool has run, which may be
// minutes, and a write deadline set at the start would cut a correct reply;
// the call's own timeout and the client's context bound that wait.
var defaultHTTPLimits = httpLimits{ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 60 * time.Second, IdleTimeout: 120 * time.Second, MaxHeaderBytes: 32 << 10}
func newHTTPServer(h http.Handler, lim httpLimits) *http.Server {
return &http.Server{Handler: h, ReadHeaderTimeout: lim.ReadHeaderTimeout, ReadTimeout: lim.ReadTimeout, IdleTimeout: lim.IdleTimeout, MaxHeaderBytes: lim.MaxHeaderBytes}
}
// loopbackAddr checks that addr (host:PORT) names only loopback addresses
// and returns the address to bind: a literal loopback IP is kept; a name is
// resolved with lookup, every address it resolves to must be loopback (one
// that is not refuses the name: a name that resolves to a LAN address today
// and to both tomorrow is not a loopback name), and the first, an IPv4 one
// when there is one, is bound, so that what is checked is what is bound. A
// bare port (no host) would bind every interface and is refused.
func loopbackAddr(ctx context.Context, addr string, lookup func(context.Context, string) ([]string, error)) (string, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return "", fmt.Errorf("%q is not HOST:PORT", addr)
}
if host == "" {
return "", errors.New("no host: an empty host binds every interface")
}
if ip := net.ParseIP(host); ip != nil {
if !ip.IsLoopback() {
return "", fmt.Errorf("%s is not a loopback address", ip)
}
return net.JoinHostPort(ip.String(), port), nil
}
lctx, lcancel := context.WithTimeout(ctx, 5*time.Second)
defer lcancel()
addrs, err := lookup(lctx, host)
if err != nil || len(addrs) == 0 {
return "", fmt.Errorf("%q does not resolve", host)
}
var first net.IP
for _, a := range addrs {
ip := net.ParseIP(a)
if ip == nil || !ip.IsLoopback() {
return "", fmt.Errorf("%q resolves to %s, which is not a loopback address", host, a)
}
if first == nil || (first.To4() == nil && ip.To4() != nil) {
first = ip
}
}
return net.JoinHostPort(first.String(), port), nil
}
Left off the page: runMCP and runMCPContext, the command itself (the flags, the configuration and the bearer token, the open that takes the state directory’s lock or exits 3, the stdio loop and the optional HTTP server beside it, the shutdown order and the exit codes: TestAecdMCPStdio, TestAecdMCPHTTP, TestAecdMCPStopsOnASignal, TestAecdMCPHTTPServesUntilASignal, TestAecdMCPExitsAtEndOfInput, TestAecdMCPExit3WhenADaemonHoldsTheDirectory, TestAecdMCPHTTPChecksWhatWasBound).
What it offers: read_file and search_files over the workspace (mcp_serve.workspace, default Dir/mcp-workspace); memory_recall when the daemon has a memory service, for a caller that is not a private turn, so it never returns a record marked private (chapter 45) ("embedder": "" runs without one, so the capture’s server lists three tools, not four); each command tool; and, under allow_write only, write_file and, with a sandbox backend as well, execute_code. tools/list is sorted by name.
The server calls its tools directly, and a direct call skips the one check that guards the dangerous ones. The agent loop consults a tool’s NeedsApproval before it calls it (chapter 27), and write_file’s only guard against a path outside the workspace is that check: the tool returns “needs approval” for an absolute path outside, a .. that leaves, or a link that points out. The first version of serverTool skipped it, so a client of the server holding allow_write could write anywhere the daemon’s uid could, the state directory included. The server has nobody to ask (the one who could answer is the principal at the other end of a socket or a token), so the rule is that what the server lists is what it is willing to run unasked: serverTool consults NeedsApproval itself and refuses a call for which it is true, with an isError result that says so and does not repeat the path the tool resolved. execute_code, which is marked on every call, is the one stated exception: it is offered only under allow_write and a sandbox backend, and the backend is the guard. serverTool also validates the arguments against the tool’s schema before the call, whether or not the tool validates its own. TestServerWriteFileStaysInTheWorkspace refuses, and checks that nothing was written by, seven routes and writes the three inside; TestServerToolRefusesWhatNeedsApproval and TestServerToolValidatesForAToolThatDoesNot pin the rule and its exception.
What a client of the server can reach is therefore this, and the review measured it against a built daemon, route by route (no second uid was available on the host):
| Route | read_file, search_files |
write_file (allow_write) |
|---|---|---|
| an absolute path outside the workspace | “is outside the workspace” | refused: the server cannot ask |
.. and sub/../.. |
outside | refused |
| a symbolic link out, to a file or to a directory | outside; a walk does not follow a link | refused |
the state directory, LOCK, the sockets, by absolute path or .. |
outside | refused |
/proc/self/environ and links to it |
outside | not tried |
| a hard link in the workspace to a file outside it | read, and matched | refused (a second name; chapter 48) |
| a path inside the workspace | read | written |
The hard link was a stated limit in this chapter’s daemon and is half closed now. os.Root confines by path, not by inode, so the file behind a hard link is reachable by whatever name it has in the workspace, and read_file still reads it. A client cannot make one through write_file, since a name it writes is always a new regular file; only the principal can, or code in a sandbox that sees the same filesystem as the workspace (execute_code can make links inside the sandbox’s view; that is established by reading the code, since no sandbox was started to try it). The link reached the command directory too: a hard link the review planted in the workspace to a script there let write_file replace it, and the command tool then ran the replacement. Chapter 48 closes the write half: write_file on this server refuses a regular file with more than one name, so the outside file is not changed (TestMCPWriteFileRefusesHardLink), and the check is a look before the write, so a link made between the look and the write by another actor with write access to the workspace is not seen. TestServerHardLinkReadNotWritten keeps the read half and checks that a symbolic link to /proc/self/environ and one to /proc/self are refused; the limit is in DECISIONS.md. Error texts from the file tools are rewritten so that they do not repeat the host’s absolute workspace path (TestServerFileErrorsDoNotNameTheWorkspace).
A process of the same uid as the daemon gains nothing from mcp.sock that the control socket and the files did not already give it, and mcp.sock refuses another uid before reading a byte. No second uid was used to show it: TestMCPSocketPeerCheck makes the real check refuse by making the daemon’s idea of its own uid differ from the test process’s, and a mutant that turned the check off fails it. Who does gain is the holder of the bearer token on the HTTP form, and a host’s model that launches aecd mcp: either reaches the whole workspace, each command tool, and memory_recall, which is scoped to the daemon’s principal and not to the caller (the principal’s whole memory, whoever asks), and, under allow_write with a sandbox, execute_code. Whoever launches aecd mcp for a model should read that sentence as the permission it grants.
The control socket on the same codec
Chapter 40’s control socket was ported onto mcp.Message, read and written by stdio.ReadMessage and WriteMessage: one codec for the control socket, the daemon’s own MCP server and the servers it mounts over a command or a socket. The port bought one set of rules, written once and exercised by the conformance fixtures, where the control socket had a decoder of its own with rules nobody had listed. It did not keep the wire identical, and the sentence that said it would is the lesson. The port was planned as “the wire unchanged”, and TestControlWire, a recording of the exchanges the surface has (the methods the client and aecd use), passes under the old codec and under the new, byte for byte. It was a passing test of a false claim: a recording holds only the lines someone sent, and the lines that matter were the ones the new codec treats differently. A review built the binary from before the port and the binary from after it and sent both the same hand-written lines, and they answered differently in many: the old codec ran a request whose id was null or absent and answered it with id 0; refused a string id as unparseable; matched member names without regard to case; and let the last of two equal members win. The differences are now a list in DECISIONS.md and in chapter 40, and each has a case in TestControlWireChanges. The list is the accepted wire, and the chapter does not copy it. Nearly all of the change is stricter, in the direction JSON-RPC and the MCP schema point (a string id is the other way: served now, refused before), and no client in the tree breaks. An external client written against chapter 40’s first wire would meet the differences, and the cost was accepted.
The review found two defects on the way, and both came from the port. One line, an error message with no id, reached m.ID.IsStr through a nil pointer and killed the daemon; the guard is now m.ID == nil || !m.ID.Set || m.ID.IsNull || m.ID.IsStr, and TestControlSurvivesEveryMessageShape sends 90 combinations of id, method, result and error and asks for a reply after each. And daemon/shutdown cancelled the daemon’s context before the reply was written, so the connections closed under the reply and a client sometimes saw the stream end where the answer should have been; Serve now writes the reply and then runs the cancel (replyThen), and TestReplyIsWrittenBeforeTheThen holds the cancel until the client has read the reply. The control socket keeps -32001 (busy) and -32002 (no such session). They are in the range the revision calls legacy (“new implementations SHOULD NOT use codes from this sub-range at all”), and -32002 meant “resource not found” to MCP peers before 2026-07-28, but the control socket is not an MCP endpoint (no _meta, methods of its own), and renumbering would change the wire again.
Carried, and not done
Two facts about this code are left as they are, and neither comes with a promise of when. A descendant of a command server that calls setsid leaves the process group and survives the group kill, and the parent-death signal below does not reach it either; holding it needs a cgroup, which is chapter 43’s backend (the deployed daemon has one: chapter 51’s unit’s cgroup holds such a descendant; a daemon started by hand still does not), and the wall clock still ends a command tool’s call. And a cancel that lands after the loop’s last check, between it and a tool’s goroutine starting, still dispatches that call (chapter 26, item 7: the loop starts no call of a batch whose context had already ended, TestCancelledRunStartsNoTool); the transport survives it, and the wasted call remains. Three more stood here when this chapter was written, and chapter 48 closed them. A command server gets a parent-death signal (SIGTERM), and the kernel ties it to the thread that started the process, not to the process (prctl(2), PR_SET_PDEATHSIG), so Start forks on a goroutine that locks its thread and keeps it until the child exits: after the daemon’s own kill -9 (or the kernel’s OOM killer) the signal fires, and a server that ignores both SIGTERM and the end of its input still outlives the daemon in a group of its own. A connection to mcp.sock that says nothing for mcp_serve.idle (five minutes unless set, "0" for none) with no request in flight is closed. And write_file on the daemon’s server refuses a file with a second name: a hard link in the workspace is still read through the file tools, but cannot be used to replace the script a command tool runs.
Not done here, and why: outputSchema is unused and structuredContent is shown to the model only when content is empty; Info and Capabilities are subsets of the schema’s; and subscriptions/listen, tasks (moved out of the core protocol into an extension, io.modelcontextprotocol/tasks, and left out: a long-running job in this book is a daemon session or a chapter 45 worker, not a server-held handle), roots, sampling and logging (deprecated, changelog “Deprecated” 1) are not implemented.
What the revision changed
The changelog’s key changes are cited where the chapter uses them, and Check exists because of one of them (minor 10, inputSchema loosened to any 2020-12 keyword). A second supported version would cost an initialize path and connection state in both transports, which is the whole of what the redesign removed. Adoption, for a sense of where the protocol stands: Barbaste, Darrigol, Vu and Wiltberger’s source-code study of eleven coding harnesses finds “SKILL.md skills lead MCP in adoption (9/11 vs. 8/11)” (arXiv 2609.00006, abstract), the count chapter 36 cites from the same paper.
Walkthrough
The conformance fixtures
Thirty-seven fixtures under go/internal/mcp/testdata/conformance/ each name the section and URL of the rule they check, as one line of JSON with the rule’s own words. TestFixtureTable prints the table below (its output, reformatted as a table); twenty-six fixtures are server-side, four client-side (a message is fed to Classify and ResultTypeOf), seven mount-side (a tool definition is fed to Check and HeaderParams). TestConformance runs the server-side ones through stdio.Pipe (the codec and the server, no process or socket), with the seven HTTP-only ones skipped there. TestConformanceHTTP sends twenty-three of the server-side fixtures (all but the three stdio-line ones) through httptest on loopback, mirroring the headers as the client does and then applying each fixture’s overrides.
| Fixture | Side | Section of the specification |
|---|---|---|
01 request-null-id |
server | Base Protocol, Messages, Requests |
02 request-no-jsonrpc |
server | Base Protocol, Messages |
03 notification-no-reply |
server | Base Protocol, Messages, Notifications |
04 notification-with-id |
server | Base Protocol, Messages, Notifications |
05 meta-no-protocol-version |
server | Base Protocol, General fields, _meta |
06 meta-no-client-capabilities |
server | Base Protocol, General fields, _meta |
07 unsupported-protocol-version |
server | Versioning, Protocol Version Negotiation |
08 server-discover |
server | Versioning; Caching, Cacheable Results |
09 tools-list-cacheable |
server | Server Utilities, Caching, Cacheable Results |
10 tools-call-unknown-tool |
server | Server Features, Tools, Error Handling |
11 tools-call-execution-error |
server | Server Features, Tools, Error Handling |
12 tools-call-complete |
server | Server Features, Tools, Calling Tools |
13 initialize-refused |
server | Versioning, Backward Compatibility |
14 unknown-method |
server | Streamable HTTP, Protocol Version Header |
15 stdio-line-not-json |
server | Transports, stdio |
16 stdio-line-not-utf8 |
server | Transports, Messages |
17 stdio-embedded-newline |
server | Transports, stdio |
18 http-origin-not-allowed |
server | Streamable HTTP, Security & Endpoint |
19 http-mcp-method-mismatch |
server | Streamable HTTP, Server Validation |
20 http-no-protocol-version-header |
server | Streamable HTTP, Protocol Version Header |
21 http-protocol-version-mismatch |
server | Streamable HTTP, Protocol Version Header |
22 http-mcp-name-missing |
server | Streamable HTTP, Standard Request Headers |
23 http-mcp-param-mismatch |
server | Streamable HTTP, Server Behavior for Custom Headers |
24 http-get-refused |
server | Streamable HTTP, Earlier Streamable HTTP Revisions |
25 client-absent-result-type |
client | Base Protocol, Result Responses, ResultType |
26 client-unknown-result-type |
client | Base Protocol, Result Responses, ResultType |
27 client-result-and-error |
client | Base Protocol, Messages, Responses |
28 client-result-null-id |
client | Base Protocol, Result Responses |
29 mount-input-schema-null |
mount | Server Features, Tools, Data Types, Tool |
30 mount-tool-name-with-space |
mount | Server Features, Tools, Tool Names |
31 mount-ref-network-uri |
mount | Base Protocol, JSON Schema Usage, $ref Resolution |
32 mount-x-mcp-header-on-array |
mount | Streamable HTTP, Schema Extension |
33 mount-x-mcp-header-number |
mount | Streamable HTTP, Schema Extension |
34 mount-plain-tool |
mount | Server Features, Tools, Data Types, Tool |
35 mount-unsupported-keyword |
mount | Base Protocol, JSON Schema Usage, Implementation Requirements |
36 client-sends-a-response |
server | Transports, Messages |
37 tools-call-arguments-not-an-object |
server | Schema, CallToolRequestParams |
Three of them in full, one from each side. Fixture 01 is the null id: the request, and the answer a server must give (-32600, and 400 over HTTP).
{"id":"request-null-id","section":"Base Protocol, Messages, Requests","url":"https://modelcontextprotocol.io/specification/2026-07-28/basic/index#requests","rule":"Unlike base JSON-RPC, the ID MUST NOT be null.","request":{"jsonrpc":"2.0","id":null,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}},"expect":{"error":-32600,"status":400}}
Fixture 21 is the header that disagrees with the body, over HTTP only: the request is well-formed, and its MCP-Protocol-Version header says 2025-11-25 while its _meta says 2026-07-28.
{"id":"http-protocol-version-mismatch","section":"Streamable HTTP, Protocol Version Header","url":"https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#protocol-version-header","rule":"The header value MUST match the io.modelcontextprotocol/protocolVersion field in _meta; if not, the server MUST reject the request with 400 and a HeaderMismatch error.","transport":"http","request":{"jsonrpc":"2.0","id":21,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}},"http":{"headers":{"MCP-Protocol-Version":"2025-11-25"}},"expect":{"error":-32020,"status":400}}
Fixture 32 is a mount-side rule, with no request at all: a tool definition whose x-mcp-header sits under an array’s items, which a client over HTTP must exclude.
{"id":"mount-x-mcp-header-on-array","section":"Streamable HTTP, Schema Extension","url":"https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#schema-extension","rule":"x-mcp-header MUST only be applied to properties statically reachable through properties keys and of a primitive type; an annotation anywhere else makes the tool definition invalid, and clients using Streamable HTTP MUST exclude it from tools/list.","side":"mount","transport":"http","tool":{"name":"arr","inputSchema":{"type":"object","properties":{"tags":{"type":"array","items":{"type":"string","x-mcp-header":"Tag"}}}}},"expect":{"excluded":true,"reason_has":"x-mcp-header"}}
Servers on the wire
These are the daemon’s real answers. A standalone aecd mcp -config server/aecd.json on wntrmute was given seven lines on standard input (wire-in.jsonl) and ended with its input, exit status 0. Its standard output, wire-out.jsonl, is below with the requests it answers, in the order it wrote them. The requests, by id: 1 is server/discover; 2 is tools/call of greet with {"name":"Kyle"}; 3 is the same call with an extra "NAME":"x"; 4 is a legacy initialize; 5 is tools/call of write_file, which this configuration does not offer; and the two lines with no id are a line that is not JSON and a request whose id is null. Every request that has a _meta carries exactly {"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}.
{"jsonrpc":"2.0","id":1,"result":{"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"aecd","version":"0"}},"cacheScope":"public","capabilities":{"tools":{}},"instructions":"Tools of one aecd daemon over its MCP workspace.","resultType":"complete","supportedVersions":["2026-07-28"],"ttlMs":60000}}
{"jsonrpc":"2.0","id":4,"error":{"code":-32601,"message":"this server speaks protocol versions 2026-07-28 and has no initialize handshake"}}
{"jsonrpc":"2.0","id":3,"result":{"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"aecd","version":"0"}},"content":[{"type":"text","text":"invalid arguments: /NAME: additionalProperties: property not in the schema"}],"isError":true,"resultType":"complete"}}
{"jsonrpc":"2.0","error":{"code":-32700,"message":"the line is not a JSON-RPC message: invalid character 'h' in literal true (expecting 'r')"}}
{"jsonrpc":"2.0","error":{"code":-32600,"message":"not a valid JSON-RPC 2.0 request"}}
{"jsonrpc":"2.0","id":5,"error":{"code":-32602,"message":"no tool named write_file"}}
{"jsonrpc":"2.0","id":2,"result":{"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"aecd","version":"0"}},"content":[{"type":"text","text":"hello, Kyle\n"}],"resultType":"complete"}}
The discover result carries supportedVersions, the tools capability, the instructions, ttlMs and cacheScope, with the server’s identity in _meta. The legacy initialize is a protocol error naming the versions, the answer the versioning SHOULD asks for. The call with the extra property is a tool execution error (isError, a successful reply): the schema says additionalProperties: false, the validation failed, and the script never ran; it is the model that should see this one. The two unreadable lines are answered without an id. A tool the server does not have is -32602, a protocol error. The reply to the successful call, last, carries resultType, content and the identity in _meta; the order is the order the replies were written, not the order of the requests, and the one that ran a process came last.
The server’s standard error held two lines: the warning that one command tool runs on this host unsandboxed, and a line from stdio about the unreadable input (mcp/stdio: the line is not a JSON-RPC message: …).
TestCommandTransport runs the subprocess form against the test binary re-executed as a server: Discover, ListTools, an echo call, a block call that the client abandons after 100 ms (the client writes notifications/cancelled and returns), a second echo that is answered on the same stream, Close, and kill -0 on the child’s pid, which fails. TestClientAgainstHandler runs the HTTP form on loopback. TestDiscoverAndMount mounts a four-tool server under fx: three tools mounted as fx__echo, fx__fail and fx__need_input, and one excluded, bad name, with the reason. TestCommandTool runs the book’s greet.sh through ServerToolIn: {"name":"Kyle"} gives hello, Kyle; {} gives hello, world; a fail argument gives an isError result with status 3; {"name":7} gives invalid arguments and the script does not run.
One captured turn
The turn below was captured on wntrmute with the daemon’s own router: ornith-1.5-35b-a3b on 127.0.0.1:8080, loaded in /v1/models before the turn, after it and after the shutdown, with ornith-1.5-9b unloaded throughout (the capture read GET /v1/models four times, once before anything was set up and then at the three points named, wrote no model parameter and contacted no other host). It took one attempt and two completions (the two model_call spans of the trace below; route.Guard reads /v1/models before each, which is not logged). The daemon ran in the background with its PID recorded, bound to a Unix socket in the run directory and nowhere else, and started the server as its child. The daemon’s aecd.json mounts the book’s server as a command server, trusted (as this chapter’s daemon honoured it; with chapter 48’s mcp.lock rule the same file mounts the server untrusted until aecd vet mcp -write has recorded it):
{
"dir": "/home/kyle/Work/aec-runs/part7-ch44-mcp/daemon/state",
"routes": "/home/kyle/Work/aec-runs/part7-ch44-mcp/routes.json",
"windows": {"wntrmute-35b": {"size": 32768, "reserve": 2048}},
"principal": "kyle",
"embedder": "",
"snapshot": {"at_close": false},
"mcp": [
{
"name": "book",
"transport": "command",
"argv": ["/home/kyle/Work/aec-runs/part7-ch44-mcp/bin/aecd", "mcp", "-config", "/home/kyle/Work/aec-runs/part7-ch44-mcp/server/aecd.json"],
"trust": "trusted"
}
]
}
The server it launches has its own state directory, a workspace holding one file, notes.txt (“The daemon reads this through a mounted MCP tool.”), and one command tool. The script it names, greet.sh, is the book’s testdata/greet.sh copied into the server’s command directory, server/state/mcp-command/, which is where a relative argv element resolves:
{
"dir": "/home/kyle/Work/aec-runs/part7-ch44-mcp/server/state",
"routes": "/home/kyle/Work/aec-runs/part7-ch44-mcp/routes.json",
"windows": {"wntrmute-35b": {"size": 32768, "reserve": 2048}},
"principal": "kyle",
"embedder": "",
"snapshot": {"at_close": false},
"mcp_serve": {
"workspace": "/home/kyle/Work/aec-runs/part7-ch44-mcp/server/workspace",
"commands": [
{
"name": "greet",
"description": "Greets a person by name.",
"argv": ["sh", "greet.sh"],
"schema": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 40}}, "additionalProperties": false}
}
]
}
}
aecd serve -config daemon/aecd.json -v -deterministic ran in the background (standard error to serve.err), and aecd send -config daemon/aecd.json -session mcp-demo -timeout 10m sent the message, read from a file by a small script so that no text of it is on a command line: Use bookgreet to greet Kyle. Then use bookread_file to read notes.txt and tell me, in one sentence, what it says. The daemon’s log (serve.err):
mcp: book: stderr: daemon: mcp_serve: 1 command tool(s) run on this host unsandboxed (no "sandbox" is configured), with the model's arguments on stdin and in ARG_ variables
mcp: book: aecd 0: versions 2026-07-28
mcp: book: instructions (not given to the model): Tools of one aecd daemon over its MCP workspace.
mcp: book: mounted 3 tools
daemon: mcp "book": this command server runs on this host with the daemon's reach, outside any sandbox; an allowlisted environment and a process group of its own are its only containment
listening /home/kyle/Work/aec-runs/part7-ch44-mcp/daemon/state/aecd.sock
ledger: begin "JugK6EVgJUOXoCVudZohxIzysSR7ceXj" "book__greet"
ledger: begin "FkmBBUDer7RFKVQsuoECfFMO99OAmEjT" "book__read_file"
ledger: end "FkmBBUDer7RFKVQsuoECfFMO99OAmEjT" ok
ledger: end "JugK6EVgJUOXoCVudZohxIzysSR7ceXj" ok
ledger: append "mcp-demo/1" at=416 len=1028
turn mcp-demo/1: final
The first line is the child’s own warning, relayed by the daemon’s stderr relay; the second is mcp.Describe of the server’s discover result; the third is the instructions, logged and cut and given to no model; the fourth is the mount, three tools because "embedder": "" leaves the server without a memory service and so without memory_recall; the fifth is the daemon’s own warning, raised once at Open for the one command server it mounted. The ledger lines are chapter 40’s: both calls began before either ended, so the model asked for the two tools in one completion and the loop ran them together. The session file holds the transcript. Its third line is the model’s request for the two calls and its fourth and fifth are the observations, each inside the fence under the tool’s name:
{"role":"assistant","content":null,"reasoning_content":"The user wants me to greet Kyle with book__greet, then read notes.txt with book__read_file. Let me do both. These are independent calls, so I can batch them.\n","tool_calls":[{"id":"JugK6EVgJUOXoCVudZohxIzysSR7ceXj","name":"book__greet","arguments":"{\"name\":\"Kyle\"}"},{"id":"FkmBBUDer7RFKVQsuoECfFMO99OAmEjT","name":"book__read_file","arguments":"{\"path\":\"notes.txt\"}"}]}
{"role":"tool","content":[{"type":"text","text":"<<<book__greet\nhello, Kyle\nbook__greet>>>"}],"tool_call_id":"JugK6EVgJUOXoCVudZohxIzysSR7ceXj","name":"book__greet"}
{"role":"tool","content":[{"type":"text","text":"<<<book__read_file\nThe daemon reads this through a mounted MCP tool.\nbook__read_file>>>"}],"tool_call_id":"FkmBBUDer7RFKVQsuoECfFMO99OAmEjT","name":"book__read_file"}
The greet observation has no blank line before its closing fence: the content block the server sent ends in a newline (hello, Kyle\n, in the wire capture above), and ContentParts trims the trailing newlines of a run before it fences it. The trace has the two calls as tool_call spans of the first turn, named for the mounted tools, with result_kind ok:
{"trace":"mcp-demo/1","id":"d6","parent":"d2","seq":6,"kind":"tool_call","name":"book__greet","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"call_hash":"cde7ffeeea96e6f6293e8efc4e5ccf4153ba8909b5fd3010d09a3e7f1affc0d5","call_id":"JugK6EVgJUOXoCVudZohxIzysSR7ceXj","result_kind":"ok","tool":"book__greet"}}
{"trace":"mcp-demo/1","id":"d7","parent":"d2","seq":7,"kind":"tool_call","name":"book__read_file","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"call_hash":"d519f3cd5081183bb31a6fdbcd2047a3d67fed428e4fa98fc3056bcde001b841","call_id":"FkmBBUDer7RFKVQsuoECfFMO99OAmEjT","result_kind":"ok","tool":"book__read_file"}}
The clock is the deterministic 2026-10-01T00:00:00Z, so no span carries a duration. The two completions used 1358 prompt and 99 completion tokens for the request and 1474 and 34 for the answer (1354 of each prompt cached), and the run’s 2832 prompt, 133 completion and 2708 cached tokens are their sum. The model’s final text, which aecd send printed with exit status 0:
Hello, Kyle! 📄 The notes.txt file says: "The daemon reads this through a mounted MCP tool."
The model greeted in its own words and did not repeat hello, Kyle; what the capture shows is that both calls reached a process the daemon did not compile in, through prefix__name, and came back fenced. It shows what the model did on one attempt, and nothing about how often it does it. aecd shutdown exited 0; the daemon’s PID was gone by kill -0; no process was running the run directory’s aecd, which is how the server’s exit (its stdin closed, the grace, no kill needed: the log has no killed after grace line) was checked; and neither aecd.sock nor any mcp.sock was left. The configuration files, the logs, the session file and models-*.txt stay in the run directory outside the repository; they are not committed, since they hold the local model’s words and a rerun would move them.
Exercises
(a) A server answers tools/list with a tool whose inputSchema is {"type":"object","properties":{"path":{"type":"string","format":"uri"}}}. Is it mounted? If a client mounted it anyway, what would the model’s path be checked against?
Answer
It is not mounted. format is not among the twenty-three keywords or the ten annotations, so jsonschema.Unsupported reports it and Check returns “inputSchema uses keywords this book’s checker cannot apply: format”; the reason appears in the mount’s Excluded list and in the daemon’s log.
Mounted with format ignored, the model’s path would be checked for being a string and for nothing else; teaching jsonschema the keyword is chapter 25’s work.
(b) Over stdio a client sends request id 9 (a call that takes a while), then notifications/cancelled for 9, then a new request with id 9, all before the first call’s tool has returned. Trace what Serve does, and say which outcomes the specification allows.
Answer
The cancellation notification cancels the first request’s context and deletes the id from the in-flight set at once, so the new id-9 request finds the id free and is accepted. The first goroutine, when its tool returns, sees that its context was cancelled while the connection’s was not, and writes nothing; and its deferred cleanup deletes the in-flight entry only if the entry is still its own, so it does not free the second request’s id. Exactly one reply goes out under id 9, and it is the second request’s.
The reuse is outside the letter of the id rule, which forbids the id of “any other request the sender has issued and not yet received a response for”: the client has had no response to the first 9, and a cancelled request gets none. This server tolerates it by freeing the id at the cancellation, and does not produce two answers for an id that is open. If the first call had already returned before the notification was read, its reply was written, the id was already free, and the notification finds nothing to cancel.
(c) A Trusted server declares delete_row with readOnlyHint: true, which is false. The daemon crashes after the ledger’s begin for a delete_row call and before its end. What does chapter 40’s resume do under the default ResumePolicy, and what would it have done had the server been Untrusted?
Answer
Mounted.Idempotent is true for a Trusted server’s tool with readOnlyHint, and chapter 40’s Resolve marks a call that has a begin and no end for replay when the tool declares itself idempotent, whatever the policy says: the turn is erased back to its user message, only if its one open batch is all replayable and no worker batch is open, and runs again when it is next sent. So delete_row runs again then, after the crash. For an Untrusted server Idempotent is false whatever the annotation says; the default policy is abort, and the turn is not replayed.
“Trusted” is the principal’s claim that the server’s author, the only one who can make the hint true, is not lying.
(d) A tool’s schema has four x-mcp-header annotations: region (a string at the top level), n (an integer inside the object property opts), tags (on the items of an array of strings) and price (type number). Which does HeaderParams accept, and what happens to the tool over Streamable HTTP and over stdio?
Answer
The first two are valid: both are on primitive types and reachable through a chain of properties keys only (opts then n is such a chain). The third is under items and the fourth is a number, so each is invalid.
One invalid annotation invalidates the definition, and over Streamable HTTP Mount excludes the whole tool with the error naming the path; the two valid annotations do not rescue it. Over stdio the transport does not mirror headers, Mount never calls HeaderParams, and Check filters x-mcp-header out of the keywords it counts as unsupported, so the tool is mounted and the annotations are ignored. The specification permits that for a client over a transport that is not HTTP.
(e) The daemon is configured to mount {"name": "db", "transport": "http", "url": "http://10.0.0.5:8000/mcp"} with no token_env. What does Open do? Does the answer change if token_env is set?
Answer
Open fails with an error naming the server db: a cleartext http:// URL is accepted only for 127.0.0.1, localhost and ::1, and https:// anywhere. The daemon’s check does not look at token_env, so setting it changes nothing. The client has a second check of its own, which does depend on the token: it will not send one over cleartext http to a host that is not loopback. The daemon’s rule is by scheme because the configuration cannot prove an address is on an encrypted network; a tailnet’s WireGuard would make it true, and nothing in aecd.json can say so.
(f) With no sandbox configured, the server’s workspace is /srv/ws, and the command directory is /var/aec/mcp-command (Dir is /var/aec). Which of these argv values does configuration accept, and where does each resolve its script or module? (1) ["sh", "greet.sh"]; (2) ["sh", "/srv/ws/greet.sh"]; (3) ["python3", "-m", "tool"]; (4) ["/srv/ws/bin/tool"]; (5) ["sh", "../../../srv/ws/greet.sh"]; (6) ["sh", "-c", ". /srv/ws/greet.sh"].
Answer
(1) is accepted. The program sh is resolved once through the daemon’s absolute PATH elements, and greet.sh is relative to the working directory, which is Dir/mcp-command; the file must be there, put by the principal, and a client of the server cannot write it. (2) is refused: an argv element after the program that is an absolute path inside the workspace is refused whether or not the file exists, because a client can write it later. (3) is accepted: the module tool is looked for from the working directory, Dir/mcp-command, and not from the workspace. (4) is refused: ResolveProgram refuses a program that lies inside the working directory a client may write. (5) is refused: a relative element that holds a separator is joined to the command directory, /var/aec/mcp-command/../../../srv/ws/greet.sh is /srv/ws/greet.sh, and that is inside the workspace. (6) is accepted, and runs the client’s file: the check reads whole elements, and a path inside a -c string is not one. The principal who writes (6) has put a client-writable script into a shell command, which no check of elements can see.
Under a sandbox backend (2) is still refused, (4) is not checked by ResolveProgram (the backend resolves argv[0]), (5) is not read (a relative name is the workspace by construction), and the working directory is the workspace, confined by the backend.
(g) A tool called book__greet returns one text block of 65,506 bytes of ASCII, then another run returns 65,507. What does the model receive in each case?
Answer
The fence for the label book__greet costs 30 bytes: <<<book__greet and a newline (15), a newline and book__greet>>> (15). With 65,506 bytes of text the observation is 65,536 bytes, exactly MaxObservationBytes, and nothing is cut. With 65,507 it does not fit, so the budget drops by ObservationMarkerBytes (256) to 65,280, the fence takes 30, 65,250 bytes of text are kept, and a second text part, outside the fence, says “[the server’s result was cut: 257 more bytes and 0 more blocks than the 65536 (MaxObservationBytes) bytes and 64 (MaxResultBlocks) blocks kept]”. The 257 is the 256 reserved for the line and the one byte that did not fit; the figures are what a run of ContentParts on wntrmute gives for these two inputs.
(h) The caching page says “If ttlMs is negative, clients SHOULD ignore it and treat it as 0.” Write the client-side fixture that tells that reading apart from refusing the result, and say why the conformance runner cannot run it as it stands.
Answer
A fixture of side client whose message is a tools/list result with "ttlMs": -5, and an expectation the runner does not have yet: ttl_as: 0 for the page’s reading, invalid_result: true for refusing. The runner of TestConformance feeds client fixtures to Classify and ResultTypeOf, and neither reads ttlMs; the rule lives in checkCacheable, which ListTools and Discover call, so the fixture needs a runner that calls a client against a pipe server that emits the violation. That is what TestCacheableFieldsAreNumbers does: a scripted transport answers Discover with "ttlMs":-5, and the test asks for a result with TTLMs 0. The servers of this book emit 60000 or the zero value, never a negative one (the page says a server MUST NOT), so a rule about what a server emits is tested on the client by feeding it the violation.
Lab
make lab CH=44 IMPL=mine runs go/labs/ch44 against the code in go/labs/ch44/mine/mcp.go; IMPL=ref runs it against this chapter’s. You write the protocol layer from the specification’s text and the fixtures: Classify (the table above), ResultTypeOf (absent is complete; complete and input_required are known; anything else is an error, because a client that read an unknown type as complete would treat a result it does not understand as an answer), ReadMessage and WriteMessage (the newline framing: blank lines skipped, invalid UTF-8 or invalid JSON a *stdio.FramingError, a line of exactly stdio.MaxLine bytes with its newline read and one byte more a fatal framing error, a message of any size one line), and Handle for server/discover, tools/list and tools/call (the order of checks in the table above).
The tests: TestClassify runs the four client-side fixtures through your Classify and ResultTypeOf; TestFraming and TestFramingLineBound check the framing and the line bound; TestWriteLargeMessageIsOneLine writes a message over 4 KiB and requires one line; TestHandleConformance runs the nineteen server-side fixtures that are not HTTP-only through your framing and your Handle; TestReferenceClient mounts your server through the reference client over a pipe; TestEmptyCursor checks that your tools/list sends no empty nextCursor and that the reference client, reading a scripted server’s replies back through your framing, asks again when a page’s cursor is "". TestNoSecretsInTestdata is provided. Against the starter, make lab CH=44 IMPL=mine exits 2 with the string chapter 44 lab: not implemented printed 25 times, seven tests failing and nothing panicking (wntrmute). The reference passes IMPL=ref.
The fixtures are the ones in the table, so a rule the chapter missed is a fixture away from both implementations: add a file under internal/mcp/testdata/conformance/, run the lab against the reference and against yours, and see whether they agree. The lab was checked against wrong implementations of the kinds a reader makes (a null id accepted; an unknown resultType read as complete; no line bound; silence on a response a client sent; array arguments replaced by {}; a large message pretty-printed over several lines), and each fails a test. The fixtures hold one fault each, so they do not prove the order of two checks against each other, the type checks on _meta’s members, that the server’s identity is in _meta and not in the result, data.requested, or the order of tools/list: a Handle wrong in only one of those passes the lab. TestEmptyCursor tests the reference client, not a client of yours.
Further reading
- The Model Context Protocol specification, revision 2026-07-28: the overview (“Tool Safety”), Base Protocol, Versioning, Transports, with stdio and Streamable HTTP, Multi Round-Trip Requests, Cancellation, Tools, Caching, Pagination, and the Key Changes. The pages were re-fetched for this chapter on 2026-10-12 and every quotation above is from them.
- The schema,
schema/2026-07-28/schema.tsat commit4a04acdofmodelcontextprotocol/modelcontextprotocol:id?: RequestIdofJSONRPCErrorResponseat line 300,CacheableResultat line 1081 (itsttlMsat 1094),ToolAnnotationsat line 1912. - JSON-RPC 2.0 Specification, 2010 (revised 2013), the section on the response object for the
nullid. - Paul Barbaste, Tristan Darrigol, Germain Vu and Tom Wiltberger, Harness Engineering: Anatomy, Architecture, and Evolution of Coding Agents -- A Source-Code Study of Eleven Systems, 2026, for the adoption count in the abstract.
- Hermes’s MCP client at the commit read,
tools/mcp_tool.pyatcca83848, 729 lines; the lines cited are 1–3, 75–80 and 430.