# 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.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/mcp (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
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

```go
var ErrNotSent = jsonrpc.ErrNotSent
```

ErrNotSent wraps the error of a call that provably never reached the server.

```go
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

```go
func ProtocolVersions() []string
```

ProtocolVersions returns the MCP protocol versions the client speaks, newest first. It asks for the first and accepts any of them.


## ToolName

```go
func ToolName(server, name string) string
```

ToolName is the name a server's tool has in zelk: mcp\_\_server\_\_tool.


## ValidName

```go
func ValidName(name string) bool
```

ValidName reports whether name can name a server: 1 to 32 letters, digits, '\_' or '-'.


## CallResult

```go
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

```go
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

```go
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

```go
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

```go
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

```go
func (c *Client) Close() error
```

Close cancels in-flight tool calls, ends the connection and, for a stdio server, stops the process.


### Client.Info

```go
func (c *Client) Info() Info
```

Info returns what the server said about itself.


### Client.ReadResource

```go
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**

```go
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 hello
```

Output:

```text
text/plain hello
```


### Client.Reconnect

```go
func (c *Client) Reconnect(ctx context.Context) error
```

Reconnect 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

```go
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**

```go
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:notes
```

Output:

```text
Notes data:notes
```


### Client.Tools

```go
func (c *Client) Tools(ctx context.Context) ([]ToolInfo, error)
```

Tools lists the server's tools, following every page.


### Client.ZelkTools

```go
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

```go
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

```go
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

```go
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**

```go
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:

```text
{"action":"accept","content":{"name":"Ada"}}
```


### Elicitation.Fields

```go
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

```go
func (e Elicitation) Validate(content map[string]json.RawMessage) error
```

Validate checks accepted content against the schema, including required fields and unexpected keys. No defaults, credentials or other data are added.


## ElicitationHandler

```go
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

```go
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

```go
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".


## Field

```go
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.


## Info

```go
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.


## Offer

```go
type Offer map[string][]string
```

Offer names the server tools the model can see, keyed by their remote names. Each value lists top-level input properties to withhold.


## Option

```go
type Option func(*Client)
```

Option configures a Client.


### WithClock

```go
func WithClock(now func() time.Time) Option
```

WithClock supplies the clock used to gate automatic restarts. It defaults to time.Now. The clock must be safe for concurrent use.


### WithConnectionChanged

```go
func WithConnectionChanged(f func(error)) Option
```

WithConnectionChanged 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

```go
func WithElicitationHandler(h ElicitationHandler) Option
```

WithElicitationHandler 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

```go
func WithToolsChanged(f func()) Option
```

WithToolsChanged has the client call f when the server says its tool list changed. f must not block.


## ResourceCapabilities

```go
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

```go
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

```go
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

```go
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.


### HTTP

```go
func HTTP(name, url string, client *http.Client, header http.Header) Server
```

HTTP 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.


### Stdio

```go
func Stdio(name string, e env.Environment, cmd env.Cmd) Server
```

Stdio 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

```go
func (s Server) Name() string
```

Name returns the server's name.


### Server.Offering

```go
func (s Server) Offering(offer Offer) Server
```

Offering 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.

```go
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:

```text
mcp__browser__snapshot {"type":"object","properties":{},"additionalProperties":false}
mcp__browser__screenshot {"type":"object","properties":{"full":{"type":"boolean"}},"additionalProperties":false}
```


## ToolAnnotations

```go
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

```go
type ToolCapabilities struct {
	ListChanged bool `json:"listChanged,omitempty"`
}
```

ToolCapabilities describes the server's tool discovery support.


## ToolInfo

```go
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.
