mcp
import "github.com/barevoidco/zelk/core/mcp"Package mcp is zelk’s Model Context Protocol client: it connects to MCP servers and exposes their tools, resources and live form elicitation to hosts. Forms require an explicit live handler; unsupported schemas and unowned requests decline. Concurrent calls remain concurrent; stdio forms decline unless exactly one tool call is in flight. URL elicitation is not supported.
A stdio server is started through an env.Environment the host supplies, so its launcher confines the server like any other process; zelk never spawns one itself. A streamable HTTP server is reached through the host’s *http.Client. Tools from a server are never trusted: whatever a server says about a tool, zelk treats it as possibly changing anything and never re-runs it after a crash.
Variables
Section titled “Variables”var ErrNotSent = jsonrpc.ErrNotSentErrNotSent wraps the error of a call that provably never reached the server.
var ErrProtocol = errors.New("mcp: protocol error")ErrProtocol is returned for a server that broke the protocol, such as one answering with a version the client doesn’t speak.
ProtocolVersions
Section titled “ProtocolVersions”func ProtocolVersions() []stringProtocolVersions returns the MCP protocol versions the client speaks, newest first. It asks for the first and accepts any of them.
ToolName
Section titled “ToolName”func ToolName(server, name string) stringToolName is the name a server’s tool has in zelk: mcp__server__tool.
ValidName
Section titled “ValidName”func ValidName(name string) boolValidName reports whether name can name a server: 1 to 32 letters, digits, ‘_’ or ‘-’.
CallResult
Section titled “CallResult”type CallResult struct { Content []Content `json:"content"` StructuredContent json.RawMessage `json:"structuredContent,omitempty"` IsError bool `json:"isError,omitempty"`}CallResult is a tool call’s result.
Capabilities
Section titled “Capabilities”type Capabilities struct { Tools *ToolCapabilities `json:"tools,omitempty"` Resources *ResourceCapabilities `json:"resources,omitempty"`}Capabilities are the features the server advertised during initialize. A nil feature means the server does not offer it.
Client
Section titled “Client”type Client struct { // contains filtered or unexported fields}Client owns successive connections to one MCP server. It recovers known-dead transports with bounded restarts and supports explicit Reconnect. It is safe for concurrent use; Close cancels and joins its process and notification readers.
Connect
Section titled “Connect”func Connect(ctx context.Context, s Server, opts ...Option) (*Client, error)Connect connects to s and completes MCP’s initialization handshake. The client owns the connection and, for a stdio server, the process: Close ends both.
Client.CallTool
Section titled “Client.CallTool”func (c *Client) CallTool(ctx context.Context, name string, arguments json.RawMessage) (CallResult, error)CallTool calls the server’s tool name with arguments. An error wrapping ErrNotSent means the request provably never reached the server.
Client.Close
Section titled “Client.Close”func (c *Client) Close() errorClose cancels in-flight tool calls, ends the connection and, for a stdio server, stops the process.
Client.Info
Section titled “Client.Info”func (c *Client) Info() InfoInfo returns what the server said about itself.
Client.ReadResource
Section titled “Client.ReadResource”func (c *Client) ReadResource(ctx context.Context, uri string) ([]ResourceContent, error)ReadResource reads uri through this server, never through a local file or HTTP fetch. The transport bounds the response to 16 MiB. Malformed contents (including invalid base64) fail with ErrProtocol.
Example
c, closeClient := exampleResourceClient()defer closeClient()contents, err := c.ReadResource(context.Background(), "data:notes")if err != nil { panic(err)}fmt.Println(contents[0].MimeType, *contents[0].Text)// Output: text/plain helloOutput:
text/plain helloClient.Reconnect
Section titled “Client.Reconnect”func (c *Client) Reconnect(ctx context.Context) errorReconnect replaces the transport and reinitializes, even after automatic recovery was exhausted. Existing calls may end with unknown outcomes and are never replayed. ctx cancels waiting for another reconnect and initialization.
Client.Resources
Section titled “Client.Resources”func (c *Client) Resources(ctx context.Context) ([]ResourceInfo, error)Resources lists resources, following at most 100 pages and returning at most 10000 entries and 4 MiB of metadata. An overlong or cyclic listing fails with ErrProtocol. A server without resource support has an empty list.
Example
c, closeClient := exampleResourceClient()defer closeClient()resources, err := c.Resources(context.Background())if err != nil { panic(err)}for _, r := range resources { fmt.Println(r.Name, r.URI)}// Output: Notes data:notesOutput:
Notes data:notesClient.Tools
Section titled “Client.Tools”func (c *Client) Tools(ctx context.Context) ([]ToolInfo, error)Tools lists the server’s tools, following every page.
Client.ZelkTools
Section titled “Client.ZelkTools”func (c *Client) ZelkTools(ctx context.Context) ([]*tool.Tool, []event.Warning, error)ZelkTools lists the server’s tools as untrusted OriginMCP tools named mcp__server__tool. Schemas fitting the canonical subset after harmless annotation removal and object closing retain strict provider rendering. Other object-root schemas retain the server’s full contract as open JSON Schema, with authoritative local validation and non-strict rendering. Invalid schemas, nonlocal references and unusable names are skipped with a precise warning. Schema bytes have deterministic key order. If the host configured an Offer, discovery applies it before exposing any definitions.
Content
Section titled “Content”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"` Resource *EmbeddedResource `json:"resource,omitempty"`}Content is one piece of a tool’s result.
Elicitation
Section titled “Elicitation”type Elicitation struct { Mode string `json:"mode,omitempty"` Message string `json:"message"` RequestedSchema json.RawMessage `json:"requestedSchema"`}Elicitation is an untrusted server’s request for a flat form. An omitted Mode means form. URL mode and schemas outside Fields’ subset are declined.
Elicitation.Answer
Section titled “Elicitation.Answer”func (e Elicitation) Answer(answers [][]string) (ElicitationResult, error)Answer converts one textual answer per field, in Fields order, to validated form content. Nil omits an optional field; a string answer is sent literally.
Example
form := mcp.Elicitation{ Message: "Your profile?", RequestedSchema: json.RawMessage(`{"type":"object","properties":{"age":{"type":"integer","minimum":18},"name":{"type":"string"}},"required":["name"]}`),}// Fields are in name order. Nil omits an optional field; text is literal.answer, err := form.Answer([][]string{nil, {"Ada"}})if err != nil { panic(err)}raw, err := json.Marshal(answer)if err != nil { panic(err)}fmt.Println(string(raw))// Output: {"action":"accept","content":{"name":"Ada"}}Output:
{"action":"accept","content":{"name":"Ada"}}Elicitation.Fields
Section titled “Elicitation.Fields”func (e Elicitation) Fields() ([]Field, error)Fields validates the restricted schema: a flat object of strings (optional format, enum and length), numbers/integers (bounds), and booleans. Unknown keywords are refused rather than silently weakening the server’s schema.
Elicitation.Validate
Section titled “Elicitation.Validate”func (e Elicitation) Validate(content map[string]json.RawMessage) errorValidate checks accepted content against the schema, including required fields and unexpected keys. No defaults, credentials or other data are added.
ElicitationHandler
Section titled “ElicitationHandler”type ElicitationHandler func(context.Context, Elicitation) (ElicitationResult, error)ElicitationHandler answers a form during a tool call. It must honour ctx, which ends with the tool call. Errors fail closed as decline.
ElicitationResult
Section titled “ElicitationResult”type ElicitationResult struct { Action string `json:"action"` Content map[string]json.RawMessage `json:"content,omitempty"`}ElicitationResult answers a live form. Only accept carries Content; the client validates it before sending. Decline refuses; cancel dismisses.
EmbeddedResource
Section titled “EmbeddedResource”type EmbeddedResource struct { URI string `json:"uri"` Text string `json:"text,omitempty"` MimeType string `json:"mimeType,omitempty"`}EmbeddedResource is a resource a tool result carries inline, in a Content of type “resource”.
type Field struct { Name string `json:"-"` Required bool `json:"-"` Type string `json:"type"` Title string `json:"title,omitempty"` Description string `json:"description,omitempty"` Format string `json:"format,omitempty"` Enum []string `json:"enum,omitempty"` EnumNames []string `json:"enumNames,omitempty"` Minimum json.Number `json:"minimum,omitempty"` Maximum json.Number `json:"maximum,omitempty"` MinLength *int `json:"minLength,omitempty"` MaxLength *int `json:"maxLength,omitempty"` Default json.RawMessage `json:"default,omitempty"`}Field is one primitive form property. Fields returns these in name order. Defaults are never filled automatically: only reviewed human input is sent.
type Info struct { // Capabilities records the optional features the server offers. Capabilities Capabilities // Name is the client's name for the server; Protocol the protocol // version agreed. Name string Protocol string // ServerName and ServerVersion are the server's own. ServerName string ServerVersion string // Instructions are the server's instructions for using it, if any. Instructions string}Info is what a server said about itself at its most recent initialization.
type Offer map[string][]stringOffer names the server tools the model can see, keyed by their remote names. Each value lists top-level input properties to withhold.
Option
Section titled “Option”type Option func(*Client)Option configures a Client.
WithClock
Section titled “WithClock”func WithClock(now func() time.Time) OptionWithClock supplies the clock used to gate automatic restarts. It defaults to time.Now. The clock must be safe for concurrent use.
WithConnectionChanged
Section titled “WithConnectionChanged”func WithConnectionChanged(f func(error)) OptionWithConnectionChanged reports process death, broken pipes, notification-stream diagnostics, recovery, or failed recovery. Intentional Close is not reported as failure. The callback must not block; a nil error means a fresh initialization completed.
WithElicitationHandler
Section titled “WithElicitationHandler”func WithElicitationHandler(h ElicitationHandler) OptionWithElicitationHandler advertises form elicitation and answers it with h. Without a handler no elicitation capability is advertised. Calls remain concurrent: HTTP response streams identify their call; uncorrelated requests (including stdio) decline unless exactly one tool call is in flight. The handler must honour cancellation and be safe for concurrent use.
WithToolsChanged
Section titled “WithToolsChanged”func WithToolsChanged(f func()) OptionWithToolsChanged has the client call f when the server says its tool list changed. f must not block.
ResourceCapabilities
Section titled “ResourceCapabilities”type ResourceCapabilities struct { ListChanged bool `json:"listChanged,omitempty"` Subscribe bool `json:"subscribe,omitempty"`}ResourceCapabilities describes resource support. ListChanged and Subscribe are recorded for hosts; the client does not subscribe or watch for changes.
ResourceContent
Section titled “ResourceContent”type ResourceContent struct { URI string `json:"uri"` MimeType string `json:"mimeType,omitempty"` Text *string `json:"text,omitempty"` Blob *string `json:"blob,omitempty"`}ResourceContent is a text or base64 blob resource returned by resources/read. Exactly one of Text and Blob is non-nil, including for empty content.
ResourceInfo
Section titled “ResourceInfo”type ResourceInfo struct { URI string `json:"uri"` Name string `json:"name"` Description string `json:"description,omitempty"` MimeType string `json:"mimeType,omitempty"`}ResourceInfo is a resource as the server lists it.
Server
Section titled “Server”type Server struct { // contains filtered or unexported fields}Server is how to reach an MCP server: by stdio through an environment, or by streamable HTTP. It is plain configuration; Connect connects.
func HTTP(name, url string, client *http.Client, header http.Header) ServerHTTP is a server reached by MCP’s streamable HTTP transport at url, through client, with header added to every request (for its credentials). zelk never reads a proxy setting: the client decides.
func Stdio(name string, e env.Environment, cmd env.Cmd) ServerStdio is a server started as a process in e, speaking MCP on its standard input and output. Its standard error is kept out of that stream: it goes to cmd.Stderr if set, so a host can show why a server failed, and is discarded otherwise. name, 1 to 32 letters, digits, ‘_’ or ‘-’, namespaces its tools: mcp__name__tool.
Server.Name
Section titled “Server.Name”func (s Server) Name() stringName returns the server’s name.
Server.Offering
Section titled “Server.Offering”func (s Server) Offering(offer Offer) ServerOffering returns a server that exposes only the named tools to the model. A nil or empty offer exposes none. Withheld properties are absent from the model’s schema and rejected locally. Tools with missing or unshapeable schemas produce discovery warnings. The host’s Tools and CallTool methods retain their direct access to the server.
Example
A host chooses which tools and properties the model can use.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req struct { ID json.RawMessage Method string } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { panic(err) } if len(req.ID) == 0 { w.WriteHeader(http.StatusAccepted) return } var result any switch req.Method { case "initialize": result = map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"tools": map[string]any{}}} case "tools/list": result = map[string]any{"tools": []any{ map[string]any{"name": "snapshot", "inputSchema": map[string]any{"type": "object"}}, map[string]any{"name": "screenshot", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"path": map[string]any{"type": "string"}, "full": map[string]any{"type": "boolean"}}}}, map[string]any{"name": "run_code", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"code": map[string]any{"type": "string"}}}}, }} } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": result}); err != nil { panic(err) }}))defer server.Close()s := mcp.HTTP("browser", server.URL, server.Client(), nil).Offering(mcp.Offer{ "snapshot": nil, "screenshot": {"path"},})c, err := mcp.Connect(context.Background(), s)if err != nil { panic(err)}defer func() { if err := c.Close(); err != nil { panic(err) }}()tools, _, err := c.ZelkTools(context.Background())if err != nil { panic(err)}for _, t := range tools { fmt.Println(t.Descriptor().Name, string(t.InputSchema()))}// Output:// mcp__browser__snapshot {"type":"object","properties":{},"additionalProperties":false}// mcp__browser__screenshot {"type":"object","properties":{"full":{"type":"boolean"}},"additionalProperties":false}Output:
mcp__browser__snapshot {"type":"object","properties":{},"additionalProperties":false}mcp__browser__screenshot {"type":"object","properties":{"full":{"type":"boolean"}},"additionalProperties":false}ToolAnnotations
Section titled “ToolAnnotations”type ToolAnnotations struct { ReadOnlyHint bool `json:"readOnlyHint,omitempty"` IdempotentHint bool `json:"idempotentHint,omitempty"`}ToolAnnotations are the hints a server gives about a tool. They are the server’s claims: the tools ZelkTools defines record them, but as OriginMCP tools they are never treated as read-only or idempotent.
ToolCapabilities
Section titled “ToolCapabilities”type ToolCapabilities struct { ListChanged bool `json:"listChanged,omitempty"`}ToolCapabilities describes the server’s tool discovery support.
ToolInfo
Section titled “ToolInfo”type ToolInfo struct { Name string `json:"name"` Title string `json:"title,omitempty"` Description string `json:"description,omitempty"` InputSchema json.RawMessage `json:"inputSchema"` Annotations ToolAnnotations `json:"annotations"`}ToolInfo is a tool as the server lists it.