Documentation
¶
Overview ¶
Package mcp connects a dialogram tool.Registry to Model Context Protocol servers. A Client dials one server over stdio or streamable HTTP, lists the server's tools and converts each into a tool.Tool whose Fn forwards tools/call over the session; Register adds them to a registry under a per-server prefix so two servers exposing the same tool name cannot collide.
Isolation ¶
An MCP tool runs out of process by definition: the server is a child process or a remote endpoint, never a Go function in this binary. That makes the server boundary the natural isolation boundary. Any sandboxing a risky tool needs — filesystem roots, network egress rules, credential scoping, seccomp — belongs inside the server, where the capability lives. This package does not attempt to sandbox the server; it forwards calls and maps results.
Trust ¶
A server's tool list, descriptions and results are data supplied by a peer. Descriptions reach the model as part of the tool spec, and results reach it as tool_result content, so a remote server is in a position to inject instructions. Treat results from servers you do not operate as untrusted content: register them with RegisterOptions.Untrusted, which marks every successful result ProvenanceUntrusted so the loop fences it as data rather than instructions. Soft failures (MCP_TOOL_ERROR, UPSTREAM_TIMEOUT) stay bare so the loop's error_code handling is unchanged.
Servers also describe their tools with behaviour hints. Register maps them onto tool.Annotations so agent.PolicyInterceptor can pause or deny on them; see RegisterOptions for the mapping rules, in particular what an unannotated tool gets.
Result mapping ¶
A tools/call result becomes the Fn return value as follows, in order:
- IsError set: tool.Soft(ErrorCodeToolError, <joined text content>), the registry's soft-failure shape, so the model stays on its degraded-path instructions instead of seeing a hard failure.
- StructuredContent present: returned as-is (object, array or primitive, per the server's output schema).
- Otherwise: {"text": <text parts joined by newlines>} plus, when any non-text part is present, "attachments": a list of placeholders. Image and audio parts become {"type","media_type","omitted":true}; the bytes never enter the model context. Embedded resources keep their text when they carry text and are otherwise marked omitted; resource links are forwarded as metadata (uri, name, media_type).
With RegisterOptions.Untrusted every value above except a soft failure is wrapped in tool.UntrustedEnvelope, so tool.ProjectModelObservation fences it before the model reads it.
A call that outruns Options.Timeout returns tool.Soft(tool.ErrorCodeUpstreamTimeout, …), which is retryable. A call whose parent context is cancelled returns the context error as a hard error. Transport and protocol errors (unknown tool, closed session) are hard errors.
Index ¶
Constants ¶
const ( // DefaultTimeout bounds one tools/call when Options.Timeout is zero. DefaultTimeout = 60 * time.Second // ErrorCodeToolError is the soft-failure error_code emitted when the // server answers a call with IsError set. ErrorCodeToolError = "MCP_TOOL_ERROR" // DefaultName labels a server whose Options.Name is empty and whose // initialize result carries no server name. DefaultName = "mcp" )
const ErrorCodeInputUnsupported = "MCP_INPUT_UNSUPPORTED"
ErrorCodeInputUnsupported is the soft failure for a server that asks the client for something other than one elicitation at a time.
Variables ¶
var ErrClosed = errors.New("mcp: client is closed")
ErrClosed is returned by every method of a Client after Close.
Functions ¶
func Register ¶
func Register(ctx context.Context, reg *tool.Registry, c *Client, o RegisterOptions) ([]string, error)
Register lists the client's tools, filters them by Allow and Deny, prefixes their names and adds them to reg. It returns the registered (prefixed) names in the server's order.
Registration is all-or-nothing: if any prefixed name is already present in reg (or appears twice in the listing), Register returns an error and adds nothing, instead of letting tool.Registry.Register panic halfway.
Each tool's Annotations are mapped from the hints the server declared (Client.Annotations): within a declared block, omitted hints take the MCP defaults (destructive and open-world true) and Destructive is cleared on a read-only tool, as the specification makes it meaningful only when readOnlyHint is false. A tool with no annotations block gets the zero tool.Annotations — dialogram's all-false default, which agent.PolicyInterceptor treats as allowed — rather than MCP's destructive/open-world defaults, so an unannotated server is not paused or denied on every call; AssumeOpenWorld opts those undeclared tools into OpenWorld.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is one initialised MCP session. Create it with Connect; it is safe for concurrent use.
func Connect ¶
Connect dials the server described by t and completes the MCP initialize handshake. ctx bounds the handshake only; the session outlives it until Close.
func (*Client) Annotations ¶
Annotations returns the hints for the tool with the given MCP name (the name before any registration prefix), as of the most recent Tools call. ok is false when no tool of that name was listed.
func (*Client) Close ¶
Close ends the session (and, for Stdio, the child process). It is idempotent and safe to call concurrently; every call returns the result of the first.
func (*Client) Instructions ¶
Instructions returns the usage instructions the server sent during initialize, or "". Servers intend this for the system prompt.
func (*Client) Tools ¶
Tools lists the server's tools (following pagination) and converts each into a tool.Tool: Name and Description pass through, Label is the server's display title when it sent one, Schema is the MCP inputSchema as a map (or tool.Obj(nil) when absent), Annotations carry the hints the server declared (see Register for the mapping; undeclared stays zero), and Fn forwards to tools/call. The returned tools are fresh values; renaming them (as Register does) does not affect the name sent on the wire.
Each call re-lists, so a server that changes its tool set is picked up by calling Tools again. The listing also refreshes what Annotations reports.
type Hints ¶
type Hints struct {
// Title is the human-readable title from the annotations block.
Title string
// ReadOnly reports that the tool does not modify its environment.
ReadOnly bool
// Destructive reports that the tool may perform destructive updates.
Destructive bool
// Idempotent reports that repeating a call with the same arguments has
// no additional effect.
Idempotent bool
// OpenWorld reports that the tool interacts with external entities
// (web search) rather than a closed domain (a memory store).
OpenWorld bool
// Declared reports whether the server sent an annotations block at
// all. When false every other field is a default.
Declared bool
}
Hints are the MCP tool annotations as the server sent them, with the specification's defaults filled in for omitted fields (Destructive and OpenWorld default to true; ReadOnly and Idempotent default to false). Per the specification Destructive and Idempotent are only meaningful when ReadOnly is false. They are hints, not guarantees: a server can say anything about itself.
Register maps Hints onto tool.Annotations so interceptors can act on them without importing this package; see RegisterOptions for the rules.
type Options ¶
type Options struct {
// Name labels the server in registered tool names (the default
// RegisterOptions.Prefix is Name + "__") and in errors. Empty means the
// name the server advertised during initialize, falling back to
// DefaultName.
Name string
// Timeout bounds each tools/call. Zero means DefaultTimeout; a negative
// value disables the per-call bound (the caller's context still applies).
Timeout time.Duration
}
Options configures a Client.
type RegisterOptions ¶
type RegisterOptions struct {
// Prefix is prepended to every tool name. Empty means Client.Name() +
// "__" (e.g. "filesystem__read_file"), which keeps two servers that
// both export read_file apart. Set NoPrefix to register bare names.
Prefix string
// NoPrefix registers the server's names unchanged, ignoring Prefix.
NoPrefix bool
// Allow restricts registration to these MCP tool names (before the
// prefix). nil means every tool; an empty non-nil list means none —
// the same convention as tool.Registry.Visible.
Allow []string
// Deny skips these MCP tool names (before the prefix). Applied after
// Allow.
Deny []string
// Untrusted wraps every successful result from this server in
// tool.UntrustedEnvelope, so tool.ProjectModelObservation fences the
// observation (as "untrusted_content" with tool.UntrustedContentNote)
// before the model reads it. Soft failures (MCP_TOOL_ERROR,
// UPSTREAM_TIMEOUT) stay bare so the loop's error_code handling is
// unchanged. Set it for any server you do not operate.
Untrusted bool
// AssumeOpenWorld marks tools the server did not annotate as
// OpenWorld, so a deployment running agent.PolicyInterceptor with
// Policy.PauseOpenWorld pauses every undeclared remote tool. Tools
// with a declared annotations block are never overridden.
AssumeOpenWorld bool
}
RegisterOptions controls how a server's tools land in a tool.Registry.
type Stdio ¶
Stdio starts the server as a child process and speaks newline-delimited JSON-RPC over its stdin and stdout — the transport most local servers use, e.g. Command "npx", Args {"-y", "@modelcontextprotocol/server-filesystem", "/tmp"}.
Env entries (KEY=VALUE) are appended to this process's environment, a later entry overriding an earlier one with the same key; nil inherits the environment unchanged. Dir is the child's working directory (empty inherits). The child's stderr is forwarded to this process's stderr so server logs stay visible. Close terminates the child.
type StreamableHTTP ¶
StreamableHTTP connects to a server exposing the streamable HTTP transport at URL. Header is added to every request (bearer tokens, API keys); Client is the HTTP client to use and defaults to a zero http.Client (no timeout — the transport holds a long-lived SSE stream).
type Transport ¶
type Transport interface {
// contains filtered or unexported methods
}
Transport describes how to reach an MCP server. Stdio and StreamableHTTP cover the two transports the specification defines; callers never touch the SDK's transport types. A Transport value is single-use: pass a fresh one to each Connect.