mcp

package
v0.24.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcp is the bridge between weft and the Model Context Protocol, both directions over the official Go SDK (github.com/modelcontextprotocol/go-sdk, aliased `sdk` in examples — this package keeps the name `mcp`):

tools, err := mcp.Tools(ctx, sess, mcp.Prefix("gh_"))
var skipped *mcp.ImportError
if errors.As(err, &skipped) { // the good tools imported; these did not
	slog.Warn("mcp: tools skipped", "err", skipped)
	err = nil
}
mcp.AddTools(srv, lookup, refund)
mcp.Serve(srv, agt, "Support agent.")

Consuming (§7.3): the tools of a connected client session become ordinary weft tools — a RawTool per server tool, the server's schema bytes verbatim (core.ParseSchema keeps every keyword the core's Schema type cannot express). Exposing (§7.2): weft tools and whole agents register on an SDK server; every failure — undecodable arguments, a handler error, a panic — is a tool result with isError, carrying the same text weft's own model would see (ADR 0002's pinned bytes, over the wire).

The bridge is mechanical by design (ADR 0003's shape bet, measured by §7.1's corpus): field-for-field maps between two already-compatible shapes, no translation layer of its own. This package is a layer of the framework module above the core (ADR 0005, ADR 0027): it imports the core (github.com/weftbase/weft/core), the SDK (its mcp and jsonrpc packages) and the OpenTelemetry trace API (a tools/call's _meta traceparent, meta.go) — beside the standard library, nothing else — and the core never imports it or names it.

Index

Examples

Constants

View Source
const LegacyMetaCaller = "dev.weftgo/caller"

LegacyMetaCaller is MetaCaller's name before 0.23.0. weft never sends it; a served call whose _meta lacks MetaCaller is read under it, for one release, so a 0.22 client stays linked. Removed in the next release.

View Source
const LegacyMetaIdempotencyKey = "dev.weftgo/idempotency_key"

LegacyMetaIdempotencyKey is MetaIdempotencyKey's name before 0.23.0. For this one transition release an imported tool's tools/call sends the key under both names, so a 0.22 server that deduplicates on this one keeps deduplicating; Serve reads MetaIdempotencyKey, else this one — what a 0.22 client sends. A server that deduplicates should do the same. Removed (sent and read) in the next release.

View Source
const MetaCaller = "ai.weftbase/caller"

MetaCaller is the params._meta key a tools/call names its weft caller under: {"run_id": "<run>", "call_id": "<tool call>"}.

View Source
const MetaIdempotencyKey = "ai.weftbase/idempotency_key"

MetaIdempotencyKey is the params._meta key every tools/call carries its core.Call.IdempotencyKey under — always, whether or not the caller link is sent: a server that deduplicates on it applies a call retried after a lost answer once (WR-8). Serve hands it to the served tool's handler as its Call.IdempotencyKey.

Variables

View Source
var ErrToolError = errors.New("mcp: tool returned an error")

ErrToolError is the cause on a remote isError result — data for the model, a sentinel for middleware.

Functions

func AddTools

func AddTools(s *sdk.Server, tools ...*core.ToolDef)

AddTools registers weft tools on an MCP server. Each tool is listed under its own name, description, input schema and — for a non-string output — output schema, and a call runs ToolDef.Invoke: the result text is returned as one text content item (and, when the tool has an output schema, as structuredContent holding the same JSON), and every failure — undecodable arguments, a handler error, a panic — is a tool result with isError, carrying the same text weft's loop would show its own model (ADR 0002's pinned bytes, over the wire). Run policy (Timeout, MaxResultBytes, WrapTools) is not applied: the exposition is the tool, not an agent; use Serve to export an agent's tools under its chain.

AddTools panics on a nil tool, a duplicate name within one call (the SDK replaces same-named tools silently and exposes no lookup, so a name already registered by an earlier call is replaced, not refused), or a tool built with RequireApproval — MCP has no approval channel, and running a gated tool unapproved would be a silent policy bypass.

Example

AddTools registers weft tools on an MCP server: the listing and the calls run the tool's own contract — no adapter layer, the tool is the exposition.

package main

import (
	"context"
	"fmt"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mcp"
)

func main() {
	echo := weft.Tool("echo", "Echo the text.",
		func(_ context.Context, in struct {
			Text string `json:"text"`
		}) (string, error) {
			return "heard: " + in.Text, nil
		})
	srv := sdk.NewServer(&sdk.Implementation{Name: "demo", Version: "0"}, nil)
	mcp.AddTools(srv, echo)

	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	client := sdk.NewClient(&sdk.Implementation{Name: "demo-client", Version: "0"}, nil)
	sess, err := client.Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}
	res, err := sess.CallTool(context.Background(), &sdk.CallToolParams{
		Name:      "echo",
		Arguments: map[string]any{"text": "hello"},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].(*sdk.TextContent).Text)
}
Output:
heard: hello

func Serve

func Serve(s *sdk.Server, a *core.Agent, description string)

Serve exposes an agent over MCP: one tool named after the agent (core.Name is required) that runs it on a prompt and returns its final text or submitted output, plus the agent's tools, each dispatched through the agent's tool chain (Agent.CallTool) so middleware and approval policy apply — an approval-gated tool answers with the ErrApprovalRequired text rather than running, loud where AddTools refuses outright. Each of those tools' calls runs as the loop would run it (core.Agent.ServeCall): under the tool's Timeout, else the agent's ("tool X timed out after d"; "OUTCOME_UNKNOWN: …" for a tool that is not ReplaySafe — its handler is abandoned and may still complete), with the result cap (the tool's MaxResultBytes, else the agent's) and panic containment. The SDK bounds nothing: a call with no Timeout runs until it answers or the client cancels it. An OUTCOME_UNKNOWN answer goes out as an ordinary isError result — MCP carries no unknown-outcome signal — so a weft client importing the tool (Tools) reads it as ErrToolError with that text, not as core.ErrOutcomeUnknown: the type is lost after one hop.

A served tool's handler reads its call with core.CallFromContext. Its IdempotencyKey is the client's: params._meta's MetaIdempotencyKey (else, for one release, LegacyMetaIdempotencyKey) — what an imported weft tool always sends, the same on a retry — so a deduplicating handler applies a retried tools/call once. A request with no key carries none (empty: the SDK hands a handler no JSON-RPC request id, and a key weft invented would differ on a retry or collide across sessions — dedupe needs the client's own). Its CallID is derived from the key when there is one ("mcp_" and 24 hex digits of its SHA-256), else "mcp_<session>_<n>": the session's id (a random instance id per Serve when the transport names none) and this Serve's count — for audit lines, not identity.

The agent tool runs the agent as a child run (a Subagent): a call the child parks for approval cannot be decided over MCP — the tool answers with the pending error and the child run's work so far is lost; a served agent whose tools need approval is served for reads only.

The agent tool is core.Subagent under the name: the same {"prompt": string} input schema, the same Output handling, the same final-text rule — Serve is Subagent over the wire. description is what MCP clients (and their models) read to decide when to call the agent: it is the whole routing surface, as for Subagent, and it is written by the caller, never synthesised. The agent tool is registered with AddTools, not dispatched through ServeCall: it runs as AddTools runs any tool (ToolDef.Invoke, panics contained) — no WrapTools chain, no Timeout and no result cap of the agent's apply to it; the child run's own budgets (MaxSteps, UsageLimit, its tools' Timeouts) and the client's cancellation bound it.

The tools exposed are the agent's registered ones (Agent.Tools); a ToolSource's snapshot is a per-step, runtime list and is not enumerated — its tools still run inside the agent tool's own steps.

A caller that sends its trace context and weft call in params._meta (traceparent, MetaCaller — this package's imported tools do under CallerMeta) is linked: the served run's invoke_agent span links to the caller's span (its own trace, never the caller's child), and the run records weft.caller.run.id / weft.caller.call.id and weft.caller.remote — a link, never parenthood, and readers keep the run top-level (meta.go). AddTools' tools read the same _meta, for a run a handler starts.

Serve panics on a nil agent, an unnamed agent (the manifest's rule), or a name collision between the agent and one of its tools.

Example

Serve exposes a whole agent as one MCP tool — named after the agent, described for routing — plus the agent's tools under its chain.

package main

import (
	"context"
	"fmt"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mcp"
	"github.com/weftbase/weft/wefttest"
)

func main() {
	agt := weft.New(wefttest.Script(wefttest.Say("research complete")),
		weft.Name("research"),
		weft.Instructions("You research."),
	)
	srv := sdk.NewServer(&sdk.Implementation{Name: "demo", Version: "0"}, nil)
	mcp.Serve(srv, agt, "Research a topic in depth.")

	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	client := sdk.NewClient(&sdk.Implementation{Name: "demo-client", Version: "0"}, nil)
	sess, err := client.Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}
	res, err := sess.CallTool(context.Background(), &sdk.CallToolParams{
		Name:      "research",
		Arguments: map[string]any{"prompt": "the history of denim"},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Content[0].(*sdk.TextContent).Text)
}
Output:
research complete

func Tools

func Tools(ctx context.Context, sess *sdk.ClientSession, opts ...Option) ([]*core.ToolDef, error)

Tools lists the tools of a connected MCP session and returns each as a weft tool: the server's name and description, its input schema as the SDK received it — every keyword preserved, an enum or a oneOf the core cannot express reaching the model whole (the SDK's client hands over decoded JSON, so the kept bytes are the document in encoding/json's canonical key order) — and a handler that forwards the model's argument bytes to tools/call. A remote result is returned as text (structuredContent's JSON when the server sends it, else the text items joined by newlines; non-text items render as one-line markers, because weft's transcript carries no binary tool results); a remote isError result is a tool error carrying the server's text verbatim (errors.Is ErrToolError; an empty one reads ErrToolError's own text); a JSON-RPC error answer (the server's handler failed, the tool is not listed) is a tool error reading "mcp: <err>", and so is a call that provably never left the client (a refused dial, a session already closed). A transport failure after the request may have been sent — the connection dropped, the stream ended — is an unknown outcome (core.ErrOutcomeUnknown, ADR 0032): the model reads "OUTCOME_UNKNOWN: …" for an imported tool (ReplayNever unless the caller vouches otherwise; a ReplaySafe one reads "mcp: <err>"), and a weft/thread session sends it down its recovery ladder. All are data the model sees, never run errors; their execute_tool spans tell them apart by error.type — mcp_tool_error (isError), mcp_rpc_error (the server refused the call) and mcp_transport (no answer).

An unknown outcome does not survive an MCP hop as a type. A tool served by a weft mcp.Serve that answers OUTCOME_UNKNOWN (its handler timed out, or was cut off) sends an isError result like any other failure — MCP has no unknown-outcome signal — so the importing side reads it as a remote isError (errors.Is ErrToolError, the text verbatim, starting "OUTCOME_UNKNOWN:"), not as core.ErrOutcomeUnknown: a session's recovery ladder does not see it as unknown. Give such a tool an idempotency key end to end (the server's handler dedupes on the client's key) rather than relying on the importer's ladder.

Every imported tool names where it came from for the record (O8): its Origin is "mcp:<server>" under Server ("mcp" otherwise) and its core.OriginDetail the server, the Transport, the Prefix and its name on the server, with the tools this listing skipped — so the tools record carries source_detail per tool and skipped[] per server, and each call's execute_tool span weft.tool.origin. A transport failure (error.type mcp_transport), a JSON-RPC error answer (mcp_rpc_error) and a remote isError (mcp_tool_error) stay told apart on the span. A server that dies mid-call on a transport that never reports it (the SDK's in-memory pipe) leaves the call to its deadline — and a call whose ctx carries none (no Timeout on the tool or the agent, no deadline on the run) is bounded at one minute: past it the call reads as a lost answer (an unknown outcome, below). A Timeout through Policy replaces the default whatever its value — Policy(core.Timeout(0)) is the deliberate lift: the call runs with no deadline, as core runs any tool whose Timeout is 0 — and so does an agent's Timeout (a positive one: the agent's Timeout(0) is no default at all, and leaves the minute in place) or any deadline on ctx. A server all of whose tools were skipped imports nothing to carry the skips: ImportError.Option records them on the agent.

Imported tools are ordinary weft tools: register them with New or serve them through ToolSource; Timeout, MaxResultBytes, RequireApproval and WrapTools apply through Policy. A tool the server does not mark readOnlyHint is Sequential — foreign tools run one at a time unless the server says parallel is safe (annotations are untrusted hints; the conservative reading is the safe one). Progress notifications are not surfaced: the delegating call's ToolStart and ToolFinish bracket the remote call. Elicitation is not answered: a server that asks fails the call, as a tool error.

The SDK's client decodes the listed schema before Tools sees it, so the kept bytes are the document re-encoded: keys in canonical order, and an integer beyond 2^53 (a maximum on an id field, say) rounded through float64 — the one loss the bridge cannot avoid short of the SDK keeping raw bytes.

Tools returns when every page is listed or ctx ends; it returns the ctx error unchanged when the deadline hits mid-list. Connect several servers concurrently with an errgroup and one deadline; for a list that changes, set the SDK's ToolListChangedHandler to re-run Tools into a slice you serve through core.ToolSource, under a mutex (the SDK runs the handler on its own goroutine, the loop reads the source on the run's; ExampleTools_toolSource shows the shape) — Tools does not own the session and never closes it. The kill switch (WEFT_MODEL_REQUESTS) governs model requests; tools/call is not one, so imported tools run under deny — they are the caller's tools, like any handler that makes an HTTP call.

A tool whose output schema the server sends is recorded on the ToolDef when it is an object schema; a non-object output schema (legal per the spec) has no weft representation and is not recorded — the result text is the tool's output either way.

A tool that cannot be imported — an input schema the core cannot key on (a non-object root, a $ref root, an omitted schema), an empty name, a name no provider accepts as a function name (with the Prefix: ASCII letters, digits, _ and -, at most 64 bytes — one such tool would fail every request of the agent holding it), a name repeated in the listing (the first importable occurrence stands: an earlier entry that was itself skipped claims nothing), a nil entry — fails that tool, not the listing: the importable tools are returned and the error is an *ImportError naming each skipped tool and why (ADR 0015's 2026-09-27 amendment). A listing of more than 10,000 tools is refused whole: an error, no tools. The slice is usable whether or not err is nil; the caller decides whether a skipped tool is a warning to log or a reason to stop:

tools, err := mcp.Tools(ctx, sess)
var skipped *mcp.ImportError
if errors.As(err, &skipped) {
	slog.Warn("mcp: tools skipped", "err", skipped)
	err = nil
}
if err != nil { // a listing failure: transport, ctx
	return err
}

Nothing is dropped silently — a server with one broken tool no longer takes its ninety-nine good ones down, and the one is still named. A listing failure (transport, the ctx ending) is the ordinary error with no tools.

Example

Tools imports a server's tools as ordinary weft tools: the server's schema bytes kept whole, its annotations mapped to per-tool policy, and the calls forwarded verbatim.

package main

import (
	"context"
	"encoding/json"
	"fmt"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft/mcp"
)

func main() {
	// Stand up a remote server standing in for a real one.
	srv := sdk.NewServer(&sdk.Implementation{Name: "remote", Version: "0"}, nil)
	srv.AddTool(&sdk.Tool{
		Name:        "search",
		Description: "Search the archive.",
		InputSchema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}`),
		Annotations: &sdk.ToolAnnotations{ReadOnlyHint: true},
	}, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
		return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "3 hits"}}}, nil
	})
	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	client := sdk.NewClient(&sdk.Implementation{Name: "demo", Version: "0"}, nil)
	sess, err := client.Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}

	tools, err := mcp.Tools(context.Background(), sess, mcp.Prefix("arch_"))
	if err != nil {
		panic(err)
	}
	out, err := tools[0].Invoke(context.Background(), []byte(`{"q":"denim"}`))
	if err != nil {
		panic(err)
	}
	fmt.Println(tools[0].Name, "->", out)
}
Output:
arch_search -> 3 hits
Example (ToolSource)

ExampleTools_toolSource is the listChanged pattern: the SDK's handler re-runs Tools into a slice the agent serves through weft.ToolSource — no registry, no owned goroutine; the list is the caller's value and the loop refetches it every step.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mcp"
	"github.com/weftbase/weft/wefttest"
)

func main() {
	srv := sdk.NewServer(&sdk.Implementation{Name: "remote", Version: "0"}, nil)
	srv.AddTool(&sdk.Tool{
		Name:        "search",
		Description: "Search.",
		InputSchema: json.RawMessage(`{"type":"object"}`),
	}, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
		return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "ok"}}}, nil
	})
	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	client := sdk.NewClient(&sdk.Implementation{Name: "demo", Version: "0"}, nil)
	sess, err := client.Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}

	// The SDK runs ToolListChangedHandler on its own goroutine and the
	// loop reads the source on the run's, so the slice lives under a
	// mutex: refresh writes it, the source reads it.
	var (
		mu      sync.Mutex
		current []*weft.ToolDef
	)
	refresh := func() {
		tools, err := mcp.Tools(context.Background(), sess)
		if err == nil {
			mu.Lock()
			current = tools
			mu.Unlock()
		}
	}
	refresh()
	// A real client sets ClientOptions.ToolListChangedHandler to call
	// refresh; the served list is whatever the last refresh produced.
	agt := weft.New(wefttest.Script(wefttest.Say("ready")),
		weft.Name("importer"),
		weft.ToolSource(func() []*weft.ToolDef {
			mu.Lock()
			defer mu.Unlock()
			return current
		}))
	res, err := agt.Generate(context.Background(), weft.Prompt("status?"))
	if err != nil {
		panic(err)
	}
	mu.Lock()
	n := len(current)
	mu.Unlock()
	fmt.Println(res.Text(), "tools fetched:", n)
}
Output:
ready tools fetched: 1

Types

type ImportError

type ImportError struct {
	Skipped []SkippedTool
	// Source is the imported tools' Origin ("mcp:<server>", "mcp"):
	// the tools record's skipped[] names it (U23.2-fix).
	Source string
}

ImportError is Tools' report of the tools it could not import. It travels beside the importable tools, not instead of them — the partial-result shape *core.RunError uses (ADR 0002): the caller reads it with errors.As and decides whether a skipped tool is a warning or a stop. Unwrap exposes each tool's cause, so errors.Is against a ParseSchema failure still works through the report.

func (*ImportError) Error

func (e *ImportError) Error() string

func (*ImportError) Option

func (e *ImportError) Option() core.Option

Option records the skipped tools on an agent that offers none of the server's tools — every one was skipped, so no imported tool carries them into the tools record (core.SkippedImports, U23.2-fix). Harmless beside importable tools: the record lists each skip once.

tools, err := mcp.Tools(ctx, sess, mcp.Server("billing"))
var skipped *mcp.ImportError
if errors.As(err, &skipped) {
	opts = append(opts, skipped.Option())
}
Example

ImportError.Option: a server whose every tool was skipped imports nothing, so the agent records the skips itself — the tools record's skipped[] names them under the server's origin.

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sync"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mcp"
	"github.com/weftbase/weft/wefttest"
	"go.opentelemetry.io/otel/log"
	"go.opentelemetry.io/otel/log/embedded"
)

// toolsRecord is ExampleServer's LoggerProvider: it keeps the tools
// record's body (the catalog each run records, ADR 0028 §5).
type toolsRecord struct {
	embedded.LoggerProvider
	mu   sync.Mutex
	body string
}

type toolsLogger struct {
	embedded.Logger
	p *toolsRecord
}

func (p *toolsRecord) Logger(string, ...log.LoggerOption) log.Logger    { return toolsLogger{p: p} }
func (toolsLogger) Enabled(context.Context, log.EnabledParameters) bool { return true }
func (l toolsLogger) Emit(_ context.Context, r log.Record) {
	if r.EventName() == "weft.tools" {
		l.p.mu.Lock()
		l.p.body = r.Body().AsString()
		l.p.mu.Unlock()
	}
}

func main() {
	srv := sdk.NewServer(&sdk.Implementation{Name: "ledger", Version: "1"}, nil)
	odd := &sdk.Tool{Name: "balance", Description: "Balance.", InputSchema: json.RawMessage(`{"type":"object"}`)}
	srv.AddTool(odd, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) { return nil, nil })
	odd.InputSchema = json.RawMessage(`{"type":["object","null"]}`) // a root the core cannot key on
	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	sess, err := sdk.NewClient(&sdk.Implementation{Name: "app", Version: "1"}, nil).
		Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}
	tools, err := mcp.Tools(context.Background(), sess, mcp.Server("ledger"))
	opts := []weft.Option{weft.Tool("lookup", "Look up.", func(context.Context, struct{}) (string, error) { return "", nil })}
	var skipped *mcp.ImportError
	if errors.As(err, &skipped) {
		opts = append(opts, skipped.Option())
	}
	fmt.Println(len(tools), "imported")

	rec := &toolsRecord{}
	opts = append(opts, weft.LoggerProvider(rec), weft.Content(true))
	if _, err := weft.New(wefttest.Script(wefttest.Say("ok")), opts...).Generate(context.Background(), weft.Prompt("x")); err != nil {
		panic(err)
	}
	var body struct {
		Skipped []struct{ Name, Source string } `json:"skipped"`
	}
	rec.mu.Lock()
	_ = json.Unmarshal([]byte(rec.body), &body)
	rec.mu.Unlock()
	fmt.Println("skipped:", body.Skipped[0].Name, "from", body.Skipped[0].Source)
}
Output:
0 imported
skipped: balance from mcp:ledger

func (*ImportError) Unwrap

func (e *ImportError) Unwrap() []error

Unwrap returns each skipped tool's cause.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures one Tools call.

func CallerMeta

func CallerMeta() Option

CallerMeta makes every imported tool's call send its caller in params._meta: the W3C traceparent (and tracestate) of the execute_tool span, and MetaCaller — the weft run and tool call ids. A weft server's Serve links its run to them (meta.go). Off by default: the ids and the trace state name your runs to the server, so send them to a server you run, not to a third party's.

Example

CallerMeta opts the imported tools in to sending their caller — the tool span's traceparent and the weft run and call — in each call's params._meta, so a weft server's Serve links its run back. Off by default: use it with servers you run.

package main

import (
	"context"
	"fmt"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mcp"
	"github.com/weftbase/weft/wefttest"
)

func main() {
	helper := weft.New(wefttest.Script(wefttest.Say("helped")), weft.Name("helper"))
	srv := sdk.NewServer(&sdk.Implementation{Name: "helpers", Version: "0"}, nil)
	mcp.Serve(srv, helper, "Helps with anything.")
	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	sess, err := sdk.NewClient(&sdk.Implementation{Name: "lead", Version: "0"}, nil).
		Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}
	tools, err := mcp.Tools(context.Background(), sess, mcp.Server("helpers"), mcp.CallerMeta())
	if err != nil {
		panic(err)
	}
	fmt.Println(len(tools), tools[0].Name)
}
Output:
1 helper

func Policy

func Policy(opts ...core.ToolOption) Option

Policy applies tool options to every imported tool, after the annotation defaults — so Sequential from a missing readOnlyHint cannot be undone here, and RequireApproval is added, never removed. Timeout, MaxResultBytes, RequireApproval and WrapTools apply as on any tool; StrictInput has no effect (a RawTool receives the model's raw arguments — validation belongs to the server). Every imported tool carries core.Origin("mcp:<server>") ("mcp" without Server; the tools record's source and the execute_tool span's weft.tool.origin); a core.Origin given here overrides it.

func Prefix

func Prefix(p string) Option

Prefix prepends p to every imported tool's name — "gh_" turns "search" into "gh_search" — so two servers' tools can share one agent; the remote call still uses the server's name.

func Server

func Server(name string) Option

Server names the server the tools come from, for the observability record only (record contract §3, §4; O8): every imported tool's Origin reads "mcp:<name>" — the tools record's source, the execute_tool span's weft.tool.origin, the node Studio's call graph draws — and its source_detail names the server, the transport, the Prefix and the tool's name on the server. Without it the Origin is "mcp" and no server is named: the server's own initialize answer is untrusted, so weft never names a node after it. The name changes nothing the model sees.

Example

Server names the server an import comes from, for the record: each imported tool's source is "mcp:<name>" — the node Studio's call graph draws, each call's weft.tool.origin — and its source_detail says the server, the transport, the prefix and its name on the server. Nothing the model sees changes.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mcp"
	"github.com/weftbase/weft/wefttest"
	"go.opentelemetry.io/otel/log"
	"go.opentelemetry.io/otel/log/embedded"
)

// toolsRecord is ExampleServer's LoggerProvider: it keeps the tools
// record's body (the catalog each run records, ADR 0028 §5).
type toolsRecord struct {
	embedded.LoggerProvider
	mu   sync.Mutex
	body string
}

type toolsLogger struct {
	embedded.Logger
	p *toolsRecord
}

func (p *toolsRecord) Logger(string, ...log.LoggerOption) log.Logger    { return toolsLogger{p: p} }
func (toolsLogger) Enabled(context.Context, log.EnabledParameters) bool { return true }
func (l toolsLogger) Emit(_ context.Context, r log.Record) {
	if r.EventName() == "weft.tools" {
		l.p.mu.Lock()
		l.p.body = r.Body().AsString()
		l.p.mu.Unlock()
	}
}

func main() {
	srv := sdk.NewServer(&sdk.Implementation{Name: "billing-service", Version: "1"}, nil)
	srv.AddTool(&sdk.Tool{
		Name: "get_invoice", Description: "Status of an invoice.",
		InputSchema: json.RawMessage(`{"type":"object","properties":{"id":{"type":"string"}}}`),
	}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
		return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "unpaid"}}}, nil
	})
	serverTransport, clientTransport := sdk.NewInMemoryTransports()
	go func() { _ = srv.Run(context.Background(), serverTransport) }()
	client := sdk.NewClient(&sdk.Implementation{Name: "front-desk", Version: "1"}, nil)
	sess, err := client.Connect(context.Background(), clientTransport, nil)
	if err != nil {
		panic(err)
	}
	tools, err := mcp.Tools(context.Background(), sess,
		mcp.Server("billing"), mcp.Transport("memory"), mcp.Prefix("svc_"))
	if err != nil {
		panic(err)
	}

	rec := &toolsRecord{}
	agt := weft.New(wefttest.Script(wefttest.Say("ok")), weft.LoggerProvider(rec), weft.Content(true), tools[0])
	if _, err := agt.Generate(context.Background(), weft.Prompt("x")); err != nil {
		panic(err)
	}
	var body struct {
		Tools []struct {
			Name         string            `json:"name"`
			Source       string            `json:"source"`
			SourceDetail map[string]string `json:"source_detail"`
		} `json:"tools"`
	}
	rec.mu.Lock()
	_ = json.Unmarshal([]byte(rec.body), &body)
	rec.mu.Unlock()
	t := body.Tools[0]
	fmt.Println(t.Name, t.Source, t.SourceDetail["transport"], t.SourceDetail["remote_name"])
}
Output:
svc_get_invoice mcp:billing memory get_invoice

func Transport

func Transport(kind string) Option

Transport names how the session reaches the server — "stdio", "http", "sse", "memory", the caller's word — for the tools record's source_detail (O8). The SDK's session does not say which transport it was connected over, so the caller who connected it does. Omitted, the record names none.

type SkippedTool

type SkippedTool struct {
	Name  string
	Index int
	Err   error
}

SkippedTool is one tool Tools left out: its server-side name (empty when the name itself was the problem), its position in the listing, and why.

Directories

Path Synopsis
examples
client command
Command client consumes MCP servers as weft tools: it connects two in-memory servers concurrently under one deadline, imports their tools with per-server prefixes, registers them on a scripted agent, runs it, and prints the manifest — the imported tools' raw schemas show in it.
Command client consumes MCP servers as weft tools: it connects two in-memory servers concurrently under one deadline, imports their tools with per-server prefixes, registers them on a scripted agent, runs it, and prints the manifest — the imported tools' raw schemas show in it.
server command
Command server exposes a weft agent as an MCP server over stdio — the getting-started agent plus its lookup tool, both directions of §7 in one process:
Command server exposes a weft agent as an MCP server over stdio — the getting-started agent plus its lookup tool, both directions of §7 in one process:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL