Documentation
¶
Overview ¶
Package wakeshift wakes the AI agents that use your MCP server when something they're waiting for happens: a crawl finishes, a build fails, a message arrives.
The whole integration for a server on the official Go MCP SDK:
wake, err := wakeshift.New() // reads WAKESHIFT_KEY; without one, Wakeshift is off
crawlFinished, err := wakeshift.DefineEvent(wake, "crawl.finished", wakeshift.EventDef[jobArgs, crawl]{
Description: "A crawl finished",
})
attached := wake.Attach(srv, wakeshift.AttachOptions{})
wakeshift.AddTool(attached, &mcp.Tool{Name: "start_crawl", Description: "Crawl a site."},
func(ctx context.Context, call *wakeshift.ToolCall, in startIn) (*mcp.CallToolResult, startOut, error) {
job := uuid.NewString()
if _, err := crawlFinished.Subscribe(ctx, call, jobArgs{Job: job}, wakeshift.Once()); err != nil {
return nil, startOut{}, err
}
go startCrawl(in.URL, job)
return nil, startOut{Job: job}, nil
}, wakeshift.Subscribes(crawlFinished))
http.Handle("/mcp", attached.Handler(mcp.NewStreamableHTTPHandler(…)))
…
crawlFinished.Emit(ctx, jobArgs{Job: job}, crawl{Status: "completed", Pages: 12})
The key comes from WAKESHIFT_KEY. Without one the client is disabled: the server runs exactly as before, events and tools still work, and nothing is sent. New does no I/O.
An event that declares neither Personal, Authorize nor Public can be subscribed only by the app's own tools (AddTool, or Wrap): the safe default for IDs your tool mints. See https://wakeshift.ai/docs/go.
*Client, *Event and *Attachment are safe for concurrent use. Create one Client per process.
Advanced ¶
Apps that act for their users' agents use ActAs, Agent, AddAgent, CheckAgent, Workspace, Manifest, AgentScope, ScopeEvent and WakeLimit (https://wakeshift.ai/docs/advanced).
Example ¶
The quickstart: a crawler that wakes the conversation that started a crawl.
package main
import (
"context"
"fmt"
"log"
"log/slog"
"net/http"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/wakeshift/wakeshift-go"
)
type jobArgs struct {
Job string `json:"job"`
}
type crawl struct {
Status string `json:"status"`
Pages int `json:"pages"`
}
type startIn struct {
URL string `json:"url"`
}
type startOut struct {
Job string `json:"job"`
}
func main() {
wake, err := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
log.Fatal(err) // a malformed key
}
crawlFinished, err := wakeshift.DefineEvent(wake, "crawl.finished", wakeshift.EventDef[jobArgs, crawl]{
Description: "A crawl finished",
})
if err != nil {
log.Fatal(err)
}
srv := mcp.NewServer(&mcp.Implementation{Name: "crawler", Version: "1.0.0"}, nil)
attached := wake.Attach(srv, wakeshift.AttachOptions{})
wakeshift.AddTool(attached, &mcp.Tool{Name: "start_crawl", Description: "Crawl a site."},
func(ctx context.Context, call *wakeshift.ToolCall, in startIn) (*mcp.CallToolResult, startOut, error) {
job := "3f2a" // your tool minted the ID, so only this conversation can know it
if _, err := crawlFinished.Subscribe(ctx, call, jobArgs{Job: job}, wakeshift.Once()); err != nil {
return nil, startOut{}, err
}
return nil, startOut{Job: job}, nil
}, wakeshift.Subscribes(crawlFinished))
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, nil)
http.Handle("/example/mcp", attached.Handler(h))
// When the crawl finishes:
got, err := crawlFinished.Emit(context.Background(), jobArgs{Job: "3f2a"}, crawl{Status: "completed", Pages: 12})
fmt.Println(got.Matched, err)
}
Output: 0 <nil>
Index ¶
- Constants
- func AddTool[In, Out any](at *Attachment, t *mcp.Tool, h ToolHandler[In, Out], opts ...ToolOption)
- func BuiltinToolNames() []string
- func DecodeArgValue(v string) (string, error)
- func EncodeArgValue(s string) string
- func IsCode(err error, code Code) bool
- func RedactSecrets(text string) string
- func RequireBearer(verify auth.TokenVerifier, metadataURL string) func(http.Handler) http.Handler
- type APIError
- type Agent
- type AgentScope
- type AppInfo
- type AttachOptions
- type Attachment
- type BuiltinTools
- type Client
- func (c *Client) ActAs(ctx context.Context, workspace, agent string) (*Agent, error)
- func (c *Client) AddAgent(ctx context.Context, workspace, agent, displayName string) (string, error)
- func (c *Client) AppID(ctx context.Context) (string, error)
- func (c *Client) Attach(srv *mcp.Server, opts AttachOptions) *Attachment
- func (c *Client) CheckAgent(ctx context.Context, workspace, agent string) error
- func (c *Client) Close() error
- func (c *Client) Enabled() bool
- func (c *Client) EventSubscriptions(ctx context.Context, user string) ([]EventSubscription, error)
- func (c *Client) ForgetUser(ctx context.Context, user string) (bool, error)
- func (c *Client) Format(f fmt.State, _ rune)
- func (c *Client) GoString() string
- func (c *Client) Handler(next http.Handler, opts AttachOptions) http.Handler
- func (c *Client) Info(ctx context.Context) (AppInfo, error)
- func (c *Client) KeyID() string
- func (c *Client) LogValue() slog.Value
- func (c *Client) PublishManifest(ctx context.Context, m Manifest) error
- func (c *Client) RevokePublishURL(ctx context.Context, id string) error
- func (c *Client) String() string
- func (c *Client) Workspace(ctx context.Context, externalID, name string) (string, error)
- type Code
- type EmitOption
- type Emitted
- type Event
- func (e *Event[A, P]) CreatePublishURL(ctx context.Context, args A, opts ...PublishURLOption) (PublishURL, error)
- func (e *Event[A, P]) Emit(ctx context.Context, args A, payload P, opts ...EmitOption) (Emitted, error)
- func (e *Event[A, P]) Name() string
- func (e *Event[A, P]) Status(ctx context.Context, args A, opts ...StatusOption) (EventStatus, error)
- func (e *Event[A, P]) StatusOf(ctx context.Context, subs ...Recipient) ([]SubscriptionStatus, error)
- func (e *Event[A, P]) Subscribe(ctx context.Context, call *ToolCall, args A, opts ...SubscribeOption) (Subscription, error)
- func (e *Event[A, P]) Unsubscribe(ctx context.Context, call *ToolCall, args A) (bool, error)
- func (e *Event[A, P]) Watch(ctx context.Context, args A, check func(ctx context.Context) (P, bool, error), ...) error
- type EventDef
- type EventStatus
- type EventSubscription
- type IDOption
- type Identity
- type Issue
- type KeyInfo
- type Manifest
- type ManifestEvent
- type Option
- type PublishURL
- type PublishURLOption
- type PublishURLSigning
- type Recipient
- type RecipientOption
- type Recognized
- type Request
- type ScopeEvent
- type SessionKey
- type StatusOption
- type Subscribable
- type SubscribeOption
- type Subscribed
- type Subscriber
- type Subscription
- type SubscriptionState
- type SubscriptionStatus
- type TokenError
- type ToolCall
- type ToolHandler
- type ToolOption
- type UsageError
- type WakeLimit
- type WatchOption
Examples ¶
Constants ¶
const ( // ReasonInvalid: malformed, or its signature doesn't verify. ReasonInvalid = "invalid token" // ReasonUnknownKey: signed with a key Wakeshift doesn't publish, checked // against a JWKS fetched (recently) without error. ReasonUnknownKey = "unknown signing key" // ReasonKeysUnavailable: signed with a key the app doesn't know, and it // couldn't fetch Wakeshift's JWKS to look for it. ReasonIssuer = "another issuer" ReasonAudience = "another app" ReasonExpired = "expired" )
Why a token was refused (TokenError.Reason).
const ( // the app's tools may subscribe to. UnavailableClientUnsupported = "client_unsupported" UnavailableNoUser = "no_user" UnavailableRefused = "refused" )
Why a Subscribe was unavailable (Subscription.Reason).
Variables ¶
This section is empty.
Functions ¶
func AddTool ¶
func AddTool[In, Out any](at *Attachment, t *mcp.Tool, h ToolHandler[In, Out], opts ...ToolOption)
AddTool registers a tool that subscribes on the attachment's server, as mcp.AddTool does (it delegates to it, so the schema In and Out give, or t's own, is the tool's): the handler gets the call, a *ToolCall, for event.Subscribe. Name the events it subscribes to with Subscribes.
wakeshift.AddTool(attached, &mcp.Tool{Name: "watch_ci", Description: "Watch CI on a repo."},
func(ctx context.Context, call *wakeshift.ToolCall, in repoIn) (*mcp.CallToolResult, watchOut, error) {
_, err := ciFinished.Subscribe(ctx, call, repoArgs{Owner: in.Owner, Repo: in.Repo})
return nil, watchOut{Watching: in.Owner + "/" + in.Repo}, err
}, wakeshift.Subscribes(ciFinished))
A call that fails (an error, an isError result, output its schema refuses, a panic, a canceled request) ends the subscriptions it made. AddTool panics, as mcp.AddTool does, on a mistake in the registration: nil arguments, a built-in tool's name, an input schema that names session_key, harness or conversation_id, an output schema that names wakeshift, or another client's event. On a disabled client it registers the tool as written, and the handler gets a disabled call.
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/wakeshift/wakeshift-go"
)
type jobArgs struct {
Job string `json:"job"`
}
type crawl struct {
Status string `json:"status"`
Pages int `json:"pages"`
}
type startOut struct {
Job string `json:"job"`
}
func main() {
wake, _ := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
ciFinished, _ := wakeshift.DefineEvent(wake, "ci.finished", wakeshift.EventDef[jobArgs, crawl]{Description: "A CI run finished"})
srv := mcp.NewServer(&mcp.Implementation{Name: "ci", Version: "1.0.0"}, nil)
attached := wake.Attach(srv, wakeshift.AttachOptions{})
// The handler is go-sdk's with the call after ctx; the input is your
// own type. tools/list adds Wakeshift's arguments, and they're taken
// out before your code sees them.
wakeshift.AddTool(attached, &mcp.Tool{Name: "watch_ci", Description: "Watch a CI run."},
func(ctx context.Context, call *wakeshift.ToolCall, in jobArgs) (*mcp.CallToolResult, startOut, error) {
_, err := ciFinished.Subscribe(ctx, call, jobArgs{Job: in.Job})
return nil, startOut{Job: in.Job}, err
}, wakeshift.Subscribes(ciFinished))
fmt.Println("registered")
}
Output: registered
func BuiltinToolNames ¶
func BuiltinToolNames() []string
BuiltinToolNames is the names of Wakeshift's own tools, in every SDK: subscribe_events, unsubscribe_events, list_subscriptions and wakeshift_wait. A fresh slice each call. Use it to tell your tools from Wakeshift's (in a tools/list snapshot test, an app store listing, a filter).
func DecodeArgValue ¶
DecodeArgValue is the string EncodeArgValue encoded as v. It refuses (CodeBadArguments) anything that isn't EncodeArgValue's canonical output for UTF-8 text, and the hashed form, which can't be decoded. Its error never contains v.
func EncodeArgValue ¶
EncodeArgValue encodes any string as a routing argument value, so a case-sensitive ID (a job, a run) can name an event's arguments: a-z, 0-9, - and _ pass through, so ordinary IDs (dep-abc123) read as they are, and . escapes the rest: A-Z becomes . and the lowercase letter, and every other byte (. included) becomes .. and two lowercase hex digits. A result over 100 characters becomes ..h and 40 hex digits of the value's SHA-256, which no byte's encoding produces. Use it on every path, on events only your tools subscribe to or that are Personal; on an event with Authorize, refuse any value that isn't a canonical encoding. Encoding isn't secrecy. Never lowercase or trim a case-sensitive ID.
func IsCode ¶
IsCode reports whether err is an *APIError or a *UsageError with code.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/wakeshift/wakeshift-go"
)
func main() {
err := fmt.Errorf("emitting: %w", &wakeshift.APIError{Status: 409, Code: wakeshift.CodeIDReused, Message: "That id was used for another emit."})
fmt.Println(wakeshift.IsCode(err, wakeshift.CodeIDReused))
var apiErr *wakeshift.APIError
fmt.Println(errors.As(err, &apiErr), apiErr.Status)
}
Output: true true 409
func RedactSecrets ¶
RedactSecrets is text with every Wakeshift secret replaced by [redacted]: app keys and connector tickets (wst_), session keys (wsc_), publish URL tokens (wsp_), signing secrets (whsec_), wait-task IDs (wkt1_), subscribe vouchers (wsv_), JWS and JWT (eyJ…), and stream links (link=, link%3D, "link":"…"), bare, URL-encoded or in JSON. For paths the SDK can't reach: your own argument or body logging, proxies, error reporters.
func RequireBearer ¶
RequireBearer wraps an MCP endpoint so each request needs a bearer token verify accepts. It's the MCP SDK's auth.RequireBearerToken (tools read the TokenInfo at req.Extra.TokenInfo), except that the 401 for a refused token says error="invalid_token", so clients refresh rather than ask the user to sign in again, and each refusal is logged with its reason (a TokenError's), the client (its User-Agent) and, for an expired token, how long past expiry it was. Never the token.
verify returns an error that unwraps to auth.ErrInvalidToken for a token it refuses (a *TokenError does); any other error answers 500. The TokenInfo it returns must carry the token's expiry, which is checked here too. metadataURL is the app's protected-resource metadata.
Types ¶
type APIError ¶
type APIError struct {
Status int
Code Code
// Message is Wakeshift's own message (for Status 0, the SDK's).
Message string
// Reason, for some errors, is a category (an MCP Events callback that
// failed verification: challenge_failed, http_4xx…).
Reason string
// RequestID is the request's ID, when the answer carries one.
RequestID string
// contains filtered or unexported fields
}
APIError is talking to Wakeshift failing: an error answer (Status, Code, Message and Reason as Wakeshift sent them), or none at all (Status 0, Code CodeUnreachable or CodeTimeout, unwrapping to the transport's error). A canceled or expired ctx is never an APIError: the call returns an error that errors.Is matches to context.Canceled or context.DeadlineExceeded.
type Agent ¶
Agent is the app acting for one of its users' agents (ActAs), under the agent's grant in the workspace the app keeps for that user. Printing or logging it never shows its token.
func (*Agent) Request ¶
Request sends a request to Wakeshift's app API as the agent, with its token, for the agent's routes this package doesn't wrap (path, e.g. /api/apps/v1/agent/sessions), and decodes the answer into out (nil: ignored). A refusal is an *APIError. When ctx has a deadline, that bounds the request instead of the HTTP client's timeout, so a long poll can outlast it. The token never leaves the SDK.
type AgentScope ¶
type AgentScope struct {
Wake []ScopeEvent `json:"wake"`
Post []ScopeEvent `json:"post"`
// WakeLimits pace how often the app may wake the agent (at most Max in
// any Seconds), on top of Wakeshift's own: 10 a second, 450 per 5 minutes
// and 3,600 an hour. Wake-ups past a limit wait their turn.
WakeLimits []WakeLimit `json:"wake_limits,omitempty"`
TTLDays int `json:"ttl_days"`
// StartPrompt is what the user should say to their agent once it's
// connected (e.g. "Join a game of Nightfall"). Wakeshift shows it after
// consent. At most 120 characters.
StartPrompt string `json:"start_prompt,omitempty"`
}
type AttachOptions ¶
type AttachOptions struct {
// Identify tells who is behind a request, from the endpoint's own
// authentication. It runs lazily, at most once per HTTP request (the
// POST), with that POST's own ctx (carrying your middleware's values)
// and its request: r.Token is the bearer token RequireBearer (or
// go-sdk's auth middleware) verified, nil without one. It runs only
// when Wakeshift needs to know: a call of a tool that subscribes, a
// built-in tool, events/*, the wait tool. An error, a panic or a run
// over 10 seconds refuses Wakeshift's part of the request (Subscribe
// returns CodeIdentifyFailed); your tool's own code still runs. A
// returned Identity.Agent must come from a verified credential.
Identify func(ctx context.Context, r Request) (Identity, error)
// RequireUser refuses Wakeshift's part of a request whose Identify
// gives no user, the same way (Subscribe returns CodeUserRequired), so
// a session_key is never a bearer for its conversation. Set it
// whenever your server requires sign-in.
RequireUser bool
// Wrap names tools registered elsewhere (mcp.AddTool, srv.AddTool,
// a generated catalog) that subscribe, with the events each subscribes
// to: Wrap: map[string][]wakeshift.ToolOption{"start_crawl":
// {wakeshift.Subscribes(crawlFinished)}}. Find the call from inside the
// handler with ToolCallFrom(ctx).
Wrap map[string][]ToolOption
// WrapFunc is Wrap as a function, for tools you know only by name at
// run time: it's asked on each tools/list and tools/call about a tool
// AddTool and Wrap don't declare (never a built-in), and returns the
// tool's options as Wrap's map would, or nil for a tool that doesn't
// subscribe. Its answer isn't kept: keep it fast. A nil event or
// another client's in its options logs wrap_bad_event, and the tool is
// served unwrapped.
WrapFunc func(tool string) []ToolOption
// BuiltinTools picks Wakeshift's own tools.
BuiltinTools BuiltinTools
// IsNativeClient, for house agents only, says that a caller the SDK
// can't recognize subscribes to events itself (MCP Events). False
// leaves it to the SDK's own checks.
IsNativeClient func(ctx context.Context, r Request) bool
}
AttachOptions configure Attach (and mcpgo.Attach, and Client.Handler). The zero value is the default: no user, anonymous callers allowed, the built-in tools subscribe_events, list_subscriptions and unsubscribe_events on, and the wait tool off.
type Attachment ¶
type Attachment struct {
// contains filtered or unexported fields
}
Attachment is Wakeshift attached to one MCP server (Attach).
func (*Attachment) Handler ¶
func (at *Attachment) Handler(next http.Handler) http.Handler
Handler puts Wakeshift in front of the MCP endpoint's handler (go-sdk's mcp.NewStreamableHTTPHandler, or mcp-go's server.NewStreamableHTTPServer), after the endpoint's authentication. It's required on HTTP: without it tools still work, but Wakeshift's arguments are stripped only after your receiving middleware runs, and identify gets the session's context. On a disabled client it returns next.
func (*Attachment) Stdin ¶
func (at *Attachment) Stdin(r io.Reader) io.ReadCloser
Stdin is r, the stdin of a stdio server, with Wakeshift's arguments taken out of every tool call before the MCP library reads it, as Handler does on HTTP: no receiving middleware, hook or tool handler middleware of yours sees them, whenever it was added. On go-sdk, serve stdio with StdioTransport, which uses it (mcp-go: mcpgo.ServeStdio). Closing it closes r if r is an io.Closer. On a disabled client it reads r as it is.
func (*Attachment) StdioTransport ¶
func (at *Attachment) StdioTransport() *mcp.IOTransport
StdioTransport is go-sdk's stdio transport with Stdin in front, so no middleware of yours sees Wakeshift's arguments on stdio:
srv.Run(ctx, attached.StdioTransport())
Like mcp.StdioTransport, it never closes the process's stdin or stdout when the session ends (an mcp.IOTransport given os.Stdout itself would close stdout). On a disabled client it's a plain stdio transport.
type BuiltinTools ¶
type BuiltinTools struct {
// Wait turns on wakeshift_wait, Claude Code's wake path with nothing
// installed, on protocol 2026-07-28 (MCP tasks). While a conversation
// waits, its client holds a request to your endpoint for about 20
// seconds at a time: give the endpoint a write timeout of at least 30
// seconds.
Wait bool
// DisableSubscribe, DisableList and DisableUnsubscribe turn off
// subscribe_events, list_subscriptions and unsubscribe_events.
DisableSubscribe, DisableList, DisableUnsubscribe bool
// DisableAll turns off every built-in tool, the wait tool included.
DisableAll bool
}
BuiltinTools picks Wakeshift's own tools. The zero value is the default: subscribe_events (listed only when an event is open to it: Personal, Authorize or Public), list_subscriptions and unsubscribe_events, and not the wait tool.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an app's connection to Wakeshift, from its key (New). It has no exported fields, and printing or logging it shows only the app and the core, never the key.
func New ¶
New returns the client for the app key in WAKESHIFT_KEY (or WithKey). It does no I/O. Without a key the client is disabled: it logs that once, at info, and runs as a no-op (Enabled reports false). A malformed key, a core that isn't https:// and, with Required, a missing key are a *UsageError (CodeConfig), whose message never contains the key.
Example ¶
package main
import (
"fmt"
"log/slog"
"github.com/wakeshift/wakeshift-go"
)
func main() {
// New reads WAKESHIFT_KEY and does no I/O. Without a key the client is
// disabled: the server runs as before, and nothing is sent.
wake, err := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
fmt.Println(wake.Enabled(), err)
// A malformed key is an error, which never quotes the key.
_, err = wakeshift.New(wakeshift.WithKey("wst_not-a-key"))
fmt.Println(wakeshift.IsCode(err, wakeshift.CodeConfig))
}
Output: false <nil> true
func (*Client) ActAs ¶
ActAs returns an Agent the app can act for: one of its own users' agents, once its grant is live. Cached until shortly before the token expires.
func (*Client) AddAgent ¶
func (c *Client) AddAgent(ctx context.Context, workspace, agent, displayName string) (string, error)
AddAgent creates an agent in one of the app's workspaces (if new) and its grant for the app's manifest scope, at once. It returns the grant's ID.
func (*Client) AppID ¶
AppID is the app's ID: from an older key, which names it, or asked of Wakeshift on first need (GET /api/apps/v1/app) and kept. A failure is remembered for 30 seconds.
func (*Client) Attach ¶
func (c *Client) Attach(srv *mcp.Server, opts AttachOptions) *Attachment
Attach attaches Wakeshift to an official Go SDK server: the one call that connects the two. Call it once per server, after the last DefineEvent, then register the tools that subscribe with AddTool, and serve the server's HTTP handler through Handler (on stdio, its stdin through Stdin), so no middleware of yours sees Wakeshift's arguments:
attached := wake.Attach(srv, wakeshift.AttachOptions{Identify: identify, RequireUser: true})
wakeshift.AddTool(attached, tool, handler, wakeshift.Subscribes(crawlFinished))
http.Handle("/mcp", attached.Handler(mcp.NewStreamableHTTPHandler(…)))
Without Handler or Stdin, receiving middleware added after Attach runs first and sees them.
It adds Wakeshift's built-in tools (BuiltinTools), Wakeshift's arguments to each tool that subscribes in tools/list (stripped before your code sees them), and MCP Events for clients that speak it (unless the server already serves its own). On a disabled client it adds nothing, and Handler returns its handler as it is. A second Attach on the same server panics.
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/wakeshift/wakeshift-go"
)
type jobArgs struct {
Job string `json:"job"`
}
type crawl struct {
Status string `json:"status"`
Pages int `json:"pages"`
}
func main() {
wake, _ := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
wakeshift.DefineEvent(wake, "crawl.finished", wakeshift.EventDef[jobArgs, crawl]{Description: "A crawl finished"})
srv := mcp.NewServer(&mcp.Implementation{Name: "crawler", Version: "1.0.0"}, nil)
attached := wake.Attach(srv, wakeshift.AttachOptions{
// Identify tells who's calling, from your own verified token, once
// per HTTP request; RequireUser refuses anonymous callers.
Identify: func(ctx context.Context, r wakeshift.Request) (wakeshift.Identity, error) {
if r.Token == nil {
return wakeshift.Identity{}, nil
}
return wakeshift.Identity{User: r.Token.UserID}, nil
},
RequireUser: true,
})
next := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, nil)
// On a disabled client, Handler is next itself.
fmt.Println(attached.Handler(next) == http.Handler(next))
}
Output: true
func (*Client) CheckAgent ¶
CheckAgent reports whether the agent's grant is still live: an APIError no_grant once it's revoked, unknown_workspace once the user is forgotten. It asks Wakeshift each time.
func (*Client) Close ¶
Close stops the client's background work and waits for it: every Watch running on it returns (its check's ctx ends, and a wait between checks ends at once), and every OnSubscribe the SDK started returns (its ctx ends). After Close, Watch returns at once and OnSubscribe isn't called; emits and the rest still work. A stdio server's process ends with its main anyway, so Close matters where the process goes on: a test, or a server that stops serving and keeps running (defer wake.Close() after creating the client). It's safe to call more than once, and returns nil.
func (*Client) Enabled ¶
Enabled reports whether the client has a key. A disabled client (no key) does nothing: tools register as written, emits send nothing.
func (*Client) EventSubscriptions ¶
EventSubscriptions lists a user's live subscriptions to the app's event types (user: the app's ID for them). On a disabled client it returns CodeDisabled.
func (*Client) ForgetUser ¶
ForgetUser deletes everything Wakeshift keeps for one of the app's users (their account was deleted, or they asked to be forgotten): their workspace, sessions, subscriptions, events and deliveries, and their ID. Open streams close. It reports false if there was nothing to forget. On a disabled client it returns CodeDisabled.
func (*Client) Handler ¶
Handler is Attachment.Handler for a server built per request: Attach each server as you build it, and put one Handler around the HTTP handler that builds them. Build one AttachOptions and pass it to both, so they can't drift. Each reads its part: Handler's opts decide who's calling (Identify, RequireUser, IsNativeClient) and the wait tool (BuiltinTools.Wait) for every request it serves, and win over a server's Attach for those; each server's Attach decides its tools (Wrap, WrapFunc, BuiltinTools' other fields). On a disabled client it returns next.
h := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
srv := newServer(r)
attached := wake.Attach(srv, opts)
wakeshift.AddTool(attached, tool, handler, wakeshift.Subscribes(ev))
return srv
}, nil)
http.Handle("/mcp", wake.Handler(h, opts))
func (*Client) PublishManifest ¶
PublishManifest tells Wakeshift what the app may do, replacing what it said before: m, with the event types DefineEvent made after m.Events. An event type both defined and listed in m.Events is an error, and nothing is sent. The app needn't call it: the SDK sends the manifest automatically, merged into the one Wakeshift has (a process that serves the app's tools, Attach, on its first call about events; any process on an emit of an event Wakeshift doesn't know yet). Call it to remove an event type or clear a setting. Once it's called, m's settings are what every automatic send carries (even if this one failed), with the event types defined by then.
func (*Client) RevokePublishURL ¶
RevokePublishURL stops a publish URL working. On a disabled client it returns CodeDisabled.
type Code ¶
type Code string
Code is an error's code: one list shared by the three SDKs and Wakeshift's HTTP API. Codes Wakeshift adds later arrive as their string, so compare with IsCode rather than switching on the constants alone.
const ( CodeBadRequest Code = "bad_request" CodeBadArguments Code = "bad_arguments" CodeBadPayload Code = "bad_payload" CodeUnknownEvent Code = "unknown_event" CodeUnknownSession Code = "unknown_session" CodeUnknownConversation Code = "unknown_conversation" CodeOtherClient Code = "other_client" CodePrivateTopic Code = "private_topic" CodeSubscriptionLimit Code = "subscription_limit" CodeSubscriptionStopped Code = "subscription_stopped" CodeIDReused Code = "id_reused" CodeRateLimited Code = "rate_limited" CodeTooLarge Code = "too_large" CodeUnauthenticated Code = "unauthenticated" CodeNoGrant Code = "no_grant" CodeUnknownWorkspace Code = "unknown_workspace" CodeUnknownPublishURL Code = "unknown_publish_url" CodeBadSigningSecret Code = "bad_signing_secret" CodeUnsupported Code = "unsupported" CodeInternal Code = "internal" CodeBadResponse Code = "bad_response" CodeCallbackFailed Code = "callback_failed" // CodeUnreachable and CodeTimeout are an *APIError with Status 0: // Wakeshift didn't answer. Its Unwrap is the transport's error. CodeUnreachable Code = "unreachable" CodeTimeout Code = "timeout" // The rest are *UsageError codes. CodeConfig Code = "config" CodeDisabled Code = "disabled" CodeUndeclaredSubscribe Code = "undeclared_subscribe" CodeNoCall Code = "no_call" CodeCallEnded Code = "call_ended" CodeIdentifyFailed Code = "identify_failed" CodeUserRequired Code = "user_required" )
The codes. The first group is Wakeshift's (the HTTP API's); the rest are the SDK's own.
func CodeOf ¶
CodeOf is err's code: the Code of the *APIError or *UsageError it is or wraps, "" for any other error (or nil). Switch on it to handle several codes at once:
switch wakeshift.CodeOf(err) {
case wakeshift.CodeUnreachable, wakeshift.CodeTimeout, wakeshift.CodeRateLimited:
// retry later
}
type EmitOption ¶
type EmitOption interface {
// contains filtered or unexported methods
}
EmitOption is an option of Emit: a RecipientOption or WithID.
type Emitted ¶
type Emitted struct {
// Matched is how many subscriptions received it (0: nobody's
// subscribed), not how many agents are awake now.
Matched int `json:"matched"`
// Duplicate: a retry. An earlier Emit, the same as this one, had its
// ID, and this is that emit's result (its Matched; nothing new sent).
Duplicate bool `json:"duplicate"`
// Unmatched are the user and native recipients with no live
// subscription it reached.
Unmatched []Recipient `json:"-"`
// Ended are the subscription recipients that are no longer live:
// forget them.
Ended []Recipient `json:"-"`
// TextTrimmed: the text was over 1000 bytes, so Wakeshift trimmed it.
TextTrimmed bool `json:"text_trimmed,omitempty"`
}
Emitted is what an Emit reached.
type Event ¶
type Event[A, P any] struct { // contains filtered or unexported fields }
Event is one of the app's event types (DefineEvent).
func DefineEvent ¶
DefineEvent defines one of the app's event types on wake (enabled or not): name is what clients subscribe to (chat.message, game.turn: lowercase dot-separated words, at most 64 characters, not wakeshift.*). Define every event before Attach. Wakeshift gets it with the manifest, automatically, when the app next needs it. A mistake in def is a *UsageError (CodeConfig).
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"github.com/wakeshift/wakeshift-go"
)
func main() {
wake, _ := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
type channel struct {
Channel string `json:"channel" jsonschema:"The channel"`
}
type message struct {
From string `json:"from"`
Text string `json:"text"`
}
// Authorize opens the event to subscribe_events and native clients,
// gated: here, members of the channel.
posted, err := wakeshift.DefineEvent(wake, "chat.message", wakeshift.EventDef[channel, message]{
Description: "A new message in a channel",
Text: func(m message, c channel) string { return m.From + " in #" + c.Channel + ": " + m.Text },
Authorize: func(ctx context.Context, s wakeshift.Subscriber, c channel) (bool, error) {
return s.User != "" && c.Channel == "eng", nil // your own membership check
},
})
fmt.Println(posted.Name(), err)
}
Output: chat.message <nil>
func (*Event[A, P]) CreatePublishURL ¶
func (e *Event[A, P]) CreatePublishURL(ctx context.Context, args A, opts ...PublishURLOption) (PublishURL, error)
CreatePublishURL makes a new publish URL for this event with args (a personal event: To, the one user it's for), for services that can only send webhooks. A POST's body, a JSON object, is an occurrence's payload, checked against the event's schema. Anyone with the URL can emit until Client.RevokePublishURL, unless it has a SigningSecret: then it takes only posts signed with it. On a disabled client it returns CodeDisabled: check wake.Enabled() where a tool offers one.
func (*Event[A, P]) Emit ¶
func (e *Event[A, P]) Emit(ctx context.Context, args A, payload P, opts ...EmitOption) (Emitted, error)
Emit sends one occurrence: to everyone subscribed with arguments that match args (a personal event: to its recipients, To, ToSubscription and ToNative, at most 1,000 in one Emit). If Wakeshift doesn't know the event yet, as when the app emits at startup before any agent has connected, Emit sends the manifest (merged, so it removes nothing) and emits once more. A retry the SDK makes itself never wakes twice. On a disabled client it checks its arguments and sends nothing (Matched 0).
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"github.com/wakeshift/wakeshift-go"
)
type jobArgs struct {
Job string `json:"job"`
}
type crawl struct {
Status string `json:"status"`
Pages int `json:"pages"`
}
func main() {
wake, _ := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
turn, _ := wakeshift.DefineEvent(wake, "game.turn", wakeshift.EventDef[jobArgs, crawl]{Description: "Your move", Personal: true})
// A personal event goes to the users your own records name.
got, err := turn.Emit(context.Background(), jobArgs{Job: "t1"}, crawl{}, wakeshift.To("ada"), wakeshift.WithID("t1-move-3"))
fmt.Println(got.Matched, err)
// Without To, it's refused before anything is sent.
_, err = turn.Emit(context.Background(), jobArgs{Job: "t1"}, crawl{})
fmt.Println(wakeshift.IsCode(err, wakeshift.CodeBadArguments))
}
Output: 0 <nil> true
func (*Event[A, P]) Status ¶
func (e *Event[A, P]) Status(ctx context.Context, args A, opts ...StatusOption) (EventStatus, error)
Status says how many conversations are subscribed to this event with args (a personal event: To, the one user to count for), how many are connected now, and how. It only reads. On a disabled client it returns CodeDisabled.
func (*Event[A, P]) StatusOf ¶
func (e *Event[A, P]) StatusOf(ctx context.Context, subs ...Recipient) ([]SubscriptionStatus, error)
StatusOf reads subscriptions to this event by ID, each with the user Subscribe returned it for (Recipient's User and Subscription), up to 1,000 at once: whether each is live and its conversation connected. It only reads. On a disabled client it returns CodeDisabled.
func (*Event[A, P]) Subscribe ¶
func (e *Event[A, P]) Subscribe(ctx context.Context, call *ToolCall, args A, opts ...SubscribeOption) (Subscription, error)
Subscribe subscribes the conversation calling a tool that subscribes (call: its handler's, or ToolCallFrom(ctx)) to this event with args, or renews its subscription. The tool's result then carries what the conversation needs to be woken (one block per call, however many subscribes it makes), and if the call fails, the subscription ends.
The event must be one the tool names in Subscribes (CodeUndeclaredSubscribe otherwise). Your tool decides who may: Authorize runs only for a native caller (an MCP Events client), before it's told to subscribe. For a native caller nothing is made here: the result's State is SubscriptionNative, or SubscriptionUnavailable with a Reason. A personal event needs a user. On a disabled client it checks its arguments and returns State SubscriptionDisabled.
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/wakeshift/wakeshift-go"
)
type jobArgs struct {
Job string `json:"job"`
}
type crawl struct {
Status string `json:"status"`
Pages int `json:"pages"`
}
func main() {
wake, _ := wakeshift.New(wakeshift.WithKey(""), wakeshift.WithLogger(slog.New(slog.DiscardHandler)))
finished, _ := wakeshift.DefineEvent(wake, "crawl.finished", wakeshift.EventDef[jobArgs, crawl]{Description: "A crawl finished"})
ctx := context.Background()
// Inside a tool that subscribes, call is its handler's (or
// ToolCallFrom(ctx)). Replay also delivers an occurrence from the last
// hour, for a job that finished before the subscribe.
sub, err := finished.Subscribe(ctx, wakeshift.ToolCallFrom(ctx), jobArgs{Job: "3f2a"}, wakeshift.Once(), wakeshift.Replay(time.Hour))
fmt.Println(sub.State, err)
}
Output: disabled <nil>
func (*Event[A, P]) Unsubscribe ¶
Unsubscribe ends the calling conversation's subscription to this event with args, reporting whether one ended. For a native caller it ends the user's own (webhook) subscriptions to the event with those arguments. On a disabled client it ends nothing.
func (*Event[A, P]) Watch ¶
func (e *Event[A, P]) Watch(ctx context.Context, args A, check func(ctx context.Context) (P, bool, error), opts ...WatchOption) error
Watch checks the vendor's own status of some work until check reports done, then emits the event once with check's payload: for work that finishes with no webhook to tell you. It blocks; run it in a goroutine with a context that outlives the request:
go crawlFinished.Watch(context.WithoutCancel(ctx), jobArgs{Job: job},
func(ctx context.Context) (crawl, bool, error) {
s, err := api.Status(ctx, job)
if err != nil {
return crawl{}, false, err
}
return crawl{Status: s.State, Pages: s.Pages}, s.Done, nil
}, wakeshift.Every(10*time.Second), wakeshift.Timeout(time.Hour))
The first check runs at once, then every Every (default 30 seconds); check errors back off, and MaxErrors in a row (default 5) or one FinalIf marks stop it. At most 10 checks of a client run at once; the rest wait their turn. The emit carries WithID's ID, or one the Watch makes, on every attempt, so a webhook emitting with the same ID wins a race without a second wake; an emit error a retry could fix (Wakeshift unreachable, 429, 5xx) is retried until Timeout (default 1 hour).
It returns nil once it emitted (or another emit with the same ID got there first), and at once, without checking, on a disabled or closed client (Close stops a running Watch and waits for it to return), when a Watch of the same event and arguments is already running in this process, or when ctx is a tool call's whose Subscribe to these arguments came back unavailable or disabled. It returns ctx's error when ctx ends (or the call that started it fails), an error matching context.DeadlineExceeded at Timeout, and otherwise the check's or the emit's error, wrapped. A mistake in its options is a *UsageError.
It runs in this process only: a restart, a deploy or a frozen serverless instance ends it. Where that matters, keep the job in your own store and check it from a cron or queue.
type EventDef ¶
type EventDef[A, P any] struct { // Description says what it is, for the agent and the person: "A new // message in a channel". Required. Description string // Title is a short title, for clients that show one. Title string // Text is the line an agent reads first for an occurrence (Wakeshift // frames it as information from outside). Optional: without it, the // agent reads Description and the arguments ("A crawl finished (job // 3f2a)"). Text func(payload P, args A) string // Personal: each subscription belongs to its subscriber (Identity.User), // and Emit sends an occurrence to some of them (To), so it may carry a // subscriber's own private view. subscribe_events and native clients // may subscribe, to their own. Personal bool // Authorize, if set, opens the event to subscribe_events and native // clients, and decides each of their subscriptions (on every native // request: a poll is a request too). It runs before a tool tells a // native client to subscribe, and never for the app's own tools' // subscriptions of bridged agents (Claude Code, Codex): your tool // checks those itself. An error, a panic or a run over 10 seconds // refuses. Never decide on Subscriber.Client or Native: the client // asserts both. Authorize func(ctx context.Context, s Subscriber, args A) (bool, error) // Public opens the event to everyone: subscribe_events and native // clients (which need a user). For truly public streams only. It can't // be combined with Personal or Authorize. Public bool // DeleteOnDelivery: Wakeshift deletes an occurrence's content (its // text and payload) once it's delivered to the agent, keeping only what // it needs to show that it happened. For messages people wouldn't // expect a third party to keep, such as chat messages. DeleteOnDelivery bool // ArgsSchema and PayloadSchema, if set, are the JSON Schemas used // instead of A's and P's. ArgsSchema, PayloadSchema json.RawMessage // Topic and Filter route occurrences, if the defaults don't fit. // Default: a topic segment per required string, integer or boolean // argument ("ev/chat.message/{channel}": each value is a topic // segment, a-z 0-9 . _ -; see EncodeArgValue for case-sensitive IDs), // and an equality filter on the payload field of each optional argument // with the same name, added to Filter. Topic string Filter map[string]string // OnSubscribe, if set, runs once for each new subscription to the // event, whichever path made it: a tool's Subscribe (once the call has // succeeded; never for a renewal or a call that failed), // subscribe_events, or a native client's events/subscribe or first // events/poll. It runs in its own goroutine with a context that // outlives the request (the request doesn't wait for it), so a vendor // with no webhook can run a Watch there for every path at once; for a // tool's Subscribe, ctx carries the values of the ctx that Subscribe // was given, and s.Context the value it passed with wakeshift.Context // (the caller's credential, say): // // OnSubscribe: func(ctx context.Context, s wakeshift.Subscribed[jobArgs]) error { // key, ok := s.Context.(apiKey) // if !ok { // return nil // another instance redeemed the voucher, or subscribe_events: no caller's key here // } // crawlFinished.Watch(ctx, s.Args, checkCrawlAs(key)) // a watch_failed or watch_timeout line says why one stopped // return nil // }, // // Client.Close ends ctx and waits for it to return. An error or a // panic logs on_subscribe_failed; the subscription stands. A disabled // client never calls it. OnSubscribe func(ctx context.Context, s Subscribed[A]) error }
EventDef describes an event type: A is a subscription's arguments (what a subscriber picks), P an occurrence's payload. Their JSON Schemas come from the Go types (field names from json tags, descriptions from jsonschema tags), as the MCP SDK does for tools.
Who may subscribe is set by Personal, Authorize and Public. An event that sets none of them can be subscribed only by the app's own tools (AddTool, Wrap): no subscribe_events, no native subscription. That's the safe default for IDs your tool mints, such as jobs or crawls.
type EventStatus ¶
type EventStatus struct {
// Subscriptions: conversations subscribed (ended or expired ones
// don't count).
Subscriptions int `json:"subscriptions"`
// Connected: of those, connected now; Via says how many each way
// ("stream", "poll", "hooks", "webhook").
Connected int `json:"connected"`
Via map[string]int `json:"via"`
}
EventStatus is who is subscribed to an event with some arguments right now (Status).
type EventSubscription ¶
type EventSubscription struct {
ID string `json:"id"`
Event string `json:"event"`
Arguments json.RawMessage `json:"arguments"`
Destination string `json:"destination"` // "conversation", "webhook" or "poll"
// WebhookHost is where a webhook delivers (the host only).
WebhookHost string `json:"webhook_host,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
EventSubscription is one of a user's subscriptions to the app's event types.
type IDOption ¶
type IDOption struct {
// contains filtered or unexported fields
}
IDOption is WithID: an option of Emit and of Watch.
func WithID ¶
WithID makes an Emit idempotent for a day: a retry of the same emit (arguments, recipients and payload) with the same ID delivers once and returns the first's result, with Duplicate set. The ID on a different emit is refused (IsCode(err, CodeIDReused)), and nothing is sent: give each occurrence its own ID. On a Watch, it's the ID of the Watch's emit.
type Identity ¶
type Identity struct {
// User is the app's ID for the person ("" for none): their
// subscriptions belong to them, a personal event's subscriptions need
// one, and list_subscriptions lists theirs.
User string
// Agent is the app's agent behind the request (ActAs), if any: every
// call for the request is then the agent's, and the user is
// Agent.User(). Only from a verified credential.
Agent *Agent
// Client is the MCP client's name, for a request that doesn't carry
// one (a stateless server never sees initialize): the name the app
// knows from its own sign-in. A name the request carries wins.
Client string
}
Identity is who's behind a request to the app's MCP endpoint, as the app knows them (AttachOptions.Identify).
type Issue ¶
Issue is one thing wrong with a call's arguments or payload: what, and where (a JSON path, "" for the whole value).
type KeyInfo ¶
type KeyInfo struct {
KeyID string `json:"key_id"` // the console's key ID
Name string `json:"name"`
}
KeyInfo is one of an app's keys, as the console names it.
type Manifest ¶
type Manifest struct {
Description string `json:"description"`
// The app identifies its own users (with its own sign-in) and
// acts for their agents in workspaces Wakeshift keeps for them
// (Client.Workspace, AddAgent, ActAs).
Agent *AgentScope `json:"agent,omitempty"`
// Events are event types defined elsewhere, not with DefineEvent: the
// manifest Wakeshift gets lists these, then the ones DefineEvent made.
// Listing one DefineEvent made is an error.
Events []ManifestEvent `json:"events,omitempty"`
// OthersCanWake: your app wakes its users' agents with what other
// people and their agents do there (messages, moves), so the consent
// screen tells the person that agents of people they don't know can
// wake theirs.
OthersCanWake bool `json:"others_can_wake,omitempty"`
// PreapproveTools names your MCP tools (as your server lists them)
// that agents' programs can run without asking each time: tools that
// only read, and routine ones the agent calls on every wake that reach
// only what it already joined. Never one that deletes, spends, or
// reaches people the user hasn't chosen. When a user connects Claude
// Code or Cursor CLI, Wakeshift offers to allow exactly these, by
// name, in the same question as its install. Letters, digits, _ and -;
// at most 20.
PreapproveTools []string `json:"preapprove_tools,omitempty"`
}
Manifest is what the app may do (see the core's apps.Manifest).
type ManifestEvent ¶
type ManifestEvent struct {
Name string `json:"name"`
Description string `json:"description"`
Arguments json.RawMessage `json:"arguments,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
Topic string `json:"topic"`
Filter map[string]string `json:"filter,omitempty"`
Personal bool `json:"personal,omitempty"`
// DeleteOnDelivery: EventDef.DeleteOnDelivery.
DeleteOnDelivery bool `json:"delete_on_delivery,omitempty"`
// Subscribe is who may subscribe: "tools" (only the app's own tools)
// or "any". Left out, Wakeshift keeps what it has.
Subscribe string `json:"subscribe,omitempty"`
}
ManifestEvent is an event type in the manifest (see the core's apps.EventType). DefineEvent makes these, and the manifest lists them.
type Option ¶
type Option func(*options)
Option configures New.
func Required ¶
func Required() Option
Required makes a missing key an error, for a server that must have Wakeshift on.
func WithCore ¶
WithCore is Wakeshift's address, instead of WAKESHIFT_CORE (default https://app.wakeshift.ai). It must be https://, except for localhost, 127.0.0.1 and ::1.
func WithHTTPClient ¶
WithHTTPClient is the HTTP client requests to Wakeshift go through (default: one with a 20-second timeout). The SDK never closes it.
func WithKey ¶
WithKey is the app key to use instead of WAKESHIFT_KEY. "" (or only whitespace) means no key, never the environment: the client is disabled, or New fails with Required.
func WithLogger ¶
WithLogger is where the SDK logs (default: slog.Default(), read when it logs). slog.New(slog.DiscardHandler) silences it.
func WithMaxRetries ¶
WithMaxRetries is how many times a request is retried after a refusal that never reached Wakeshift (a load balancer's) or a connection failure (default 2; 0 turns retries off). A retried emit can't wake twice.
type PublishURL ¶
type PublishURL struct {
ID string `json:"id"`
Event string `json:"event"`
URL string `json:"url"`
// Signing is set when it was made with a SigningSecret: the secret's
// fingerprint, never the secret.
Signing *PublishURLSigning `json:"signing,omitempty"`
}
PublishURL is a capability URL that emits one event (CreatePublishURL: a POST's body is its payload). Anyone with URL can emit, so printing, logging or marshaling it elides its token: pass URL where you mean to share it.
func (PublishURL) Format ¶
func (p PublishURL) Format(f fmt.State, _ rune)
Format prints String for every verb.
func (PublishURL) LogValue ¶
func (p PublishURL) LogValue() slog.Value
LogValue logs a publish URL without its token.
func (PublishURL) MarshalJSON ¶
func (p PublishURL) MarshalJSON() ([]byte, error)
MarshalJSON marshals a publish URL without its token: pass .URL where you mean to share it.
func (PublishURL) MarshalXML ¶
func (p PublishURL) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML marshals a publish URL without its token.
func (PublishURL) String ¶
func (p PublishURL) String() string
String prints a publish URL without its token.
type PublishURLOption ¶
type PublishURLOption interface {
// contains filtered or unexported methods
}
PublishURLOption is an option of CreatePublishURL: a RecipientOption or SigningSecret.
func SigningSecret ¶
func SigningSecret(secret string) PublishURLOption
SigningSecret makes CreatePublishURL's URL take only posts signed with the sender's Standard Webhooks secret (whsec_ and the base64 of 24 to 64 bytes). It's sent to Wakeshift once and never returned: PublishURL.Signing has its fingerprint.
type PublishURLSigning ¶
type PublishURLSigning struct {
Fingerprint string `json:"fingerprint"`
SetAt time.Time `json:"set_at"`
PreviousValidUntil *time.Time `json:"previous_valid_until,omitempty"`
}
PublishURLSigning is a publish URL's signing secret as Wakeshift shows it: its fingerprint (the first 12 hex digits of its SHA-256), when it was set, and until when the previous one is still accepted.
type Recipient ¶
Recipient is one recipient of a personal event's occurrence: a user (every subscription they have to the event with the emit's arguments), one subscription of a user's (Subscription: the ID Subscribe returned, for the user it returned), or a user's native subscriptions only (Native: the ones a client that subscribes itself made).
type RecipientOption ¶
type RecipientOption struct {
// contains filtered or unexported fields
}
RecipientOption names the recipients of a personal event's occurrence (To, ToSubscription, ToNative). Emit, CreatePublishURL and Status each take one.
func To ¶
func To(users ...string) RecipientOption
To sends a personal event's occurrence to users (the app's IDs for them): only their subscriptions get it. Take the users from your own ownership record, never from who's subscribed. Repeatable, and mixable with ToSubscription and ToNative.
func ToNative ¶
func ToNative(users ...string) RecipientOption
ToNative sends a personal event's occurrence only to users' native subscriptions (made by a client that subscribes itself, with MCP Events) to the event with the emit's arguments. Repeatable.
func ToSubscription ¶
func ToSubscription(user, id string) RecipientOption
ToSubscription sends a personal event's occurrence to exactly one subscription: the one Subscribe returned (Subscription.ID), with its user (Subscription.User). One that's no longer live comes back in Emitted.Ended. Repeatable.
type Recognized ¶
type Recognized struct {
Harness string `json:"harness"`
Via string `json:"via"`
Claimed string `json:"claimed"`
}
Recognized is what Wakeshift recognized the calling conversation's harness as, and by which signal: Via is "client", "meta", "user_agent", or "claim" when only the agent's harness argument named it; both are "" when nothing named a harness (Wakeshift can't wake it, and messages are held for its next call). Claimed is what the agent said (normalized: "Grok Bot" is grok-bot), "" if it didn't; a Claimed that differs from Harness was ignored, since it contradicted what the call was recognized as.
type Request ¶
type Request struct {
// Token is the bearer token verified in front of the endpoint
// (RequireBearer, or go-sdk's auth middleware); nil without one.
Token *auth.TokenInfo
// Header is the HTTP request's header: nil off HTTP (stdio), under
// go-sdk and mcp-go alike, so `r.Header == nil` means stdio. It isn't
// verified: read identity from Token, or verify what you read.
Header http.Header
// ClientName is the MCP client's name, if the request carries one
// (client-asserted).
ClientName string
// Meta is the request's _meta.
Meta map[string]any
}
Request is a request to the app's MCP endpoint, as Identify, IsNativeClient and Authorize see it. Printing, logging or marshaling it shows only the client's name and whether it has a token, never the token or the header.
func (Request) MarshalJSON ¶
MarshalJSON gives the client's name and whether there's a token.
type ScopeEvent ¶
type SessionKey ¶
type SessionKey string
SessionKey is a conversation's session key: a bearer for the conversation (without a user), so it prints, logs, marshals and gob-encodes as [redacted]. string(k) is the key, for where you mean to use it. encoding/json writes a map key of a string type as it is, so don't key a map you marshal by it; and printers that ignore methods (reflection dumpers) print it whole: keep it out of structs you dump.
func (SessionKey) Format ¶
func (k SessionKey) Format(f fmt.State, _ rune)
Format prints String for every verb.
func (SessionKey) GobEncode ¶
func (k SessionKey) GobEncode() ([]byte, error)
GobEncode encodes it as [redacted].
func (SessionKey) LogValue ¶
func (k SessionKey) LogValue() slog.Value
LogValue logs it as [redacted].
func (SessionKey) MarshalText ¶
func (k SessionKey) MarshalText() ([]byte, error)
MarshalText marshals it as [redacted] (JSON, XML, YAML, map keys).
func (SessionKey) String ¶
func (k SessionKey) String() string
type StatusOption ¶
type StatusOption interface {
// contains filtered or unexported methods
}
StatusOption is an option of Status: a RecipientOption.
type Subscribable ¶
type Subscribable interface {
// contains filtered or unexported methods
}
Subscribable is one of the app's events, as Subscribes takes it: every *Event is one.
type SubscribeOption ¶
type SubscribeOption func(*subscribeOptions)
SubscribeOption shapes a Subscribe.
func Context ¶
func Context(v any) SubscribeOption
Context passes v to the event's OnSubscribe for the subscription this Subscribe makes (Subscribed.Context): the caller's credential, say, for a Watch that checks your API as the caller. v is yours: it's never sent to Wakeshift, logged or printed. For a native client handed a subscribe voucher, OnSubscribe gets v when the client redeems the voucher in this process within four hours; a redemption on another instance gets nil.
func Label ¶
func Label(l string) SubscribeOption
Label names a new session (agent@label), for an app acting for its agents.
func Once ¶
func Once() SubscribeOption
Once ends the subscription after its first delivery: "tell me when this finishes".
func Reason ¶
func Reason(r string) SubscribeOption
Reason says why the app subscribes the conversation, shown in the console (at most 200 characters).
func Replay ¶
func Replay(d time.Duration) SubscribeOption
Replay also delivers the latest occurrence with these arguments from this far back (more than 0, at most 24 hours), so one emitted just before the subscribe isn't missed: the answer when the job's ID exists only after it starts. Only on creation, not a renewal.
func TTL ¶
func TTL(d time.Duration) SubscribeOption
TTL ends the subscription after this long without a delivery or a fresh subscribe (default 30 days).
type Subscribed ¶
type Subscribed[A any] struct { // Args are the subscription's arguments. Args A // User is the subscriber's user (Identity.User), "" for none. User string // Via is the path that made it: "tool", "subscribe_events" or // "native". Via string // Tool is the subscribing tool's name, for Via "tool"; else "". Tool string // Context is the value the subscribing call passed Subscribe // (wakeshift.Context): for Via "tool", that call's; for a native // client's redemption of a subscribe voucher, the value of the call // that handed the voucher out, if this process still holds it (for // four hours, until it's redeemed; another instance doesn't). nil // otherwise (subscribe_events, a native subscription, a Subscribe // without Context): a Watch that needs the caller's credential can't // run as the caller then; log that, or leave the agent to the tool // that reports the work's status. Context any }
Subscribed is a new subscription, as OnSubscribe gets it.
type Subscriber ¶
type Subscriber struct {
// User is the app's ID for the person (Identity.User), if it has one.
User string
// Client is the MCP client's name, if known (client-asserted).
Client string
// Native: subscribing natively (MCP Events), not through a tool
// (client-asserted).
Native bool
// Request is the request subscribing: its verified token, header,
// client name and _meta.
Request Request
}
Subscriber is who's subscribing: what Authorize decides on. Printing or logging it shows the user and client, never the request's credentials.
func (Subscriber) Format ¶
func (s Subscriber) Format(f fmt.State, _ rune)
Format prints String for every verb.
func (Subscriber) LogValue ¶
func (s Subscriber) LogValue() slog.Value
LogValue logs the subscriber without the request's credentials.
func (Subscriber) MarshalJSON ¶
func (s Subscriber) MarshalJSON() ([]byte, error)
MarshalJSON gives the subscriber without the request's credentials.
func (Subscriber) String ¶
func (s Subscriber) String() string
type Subscription ¶
type Subscription struct {
State SubscriptionState `json:"state"`
ID string `json:"id,omitempty"`
User string `json:"user,omitempty"`
// Session is the conversation's session key (it prints as [redacted]).
Session SessionKey `json:"session,omitempty"`
// Recognized is what Wakeshift recognized the agent's program as.
Recognized Recognized `json:"recognized"`
// Reason is why it's unavailable.
Reason string `json:"reason,omitempty"`
}
Subscription is what Subscribe did. ID and User address a created or renewed one later: an Emit's ToSubscription(User, ID).
type SubscriptionState ¶
type SubscriptionState string
SubscriptionState is what a Subscribe did.
const ( // SubscriptionCreated: a new conversation subscription. SubscriptionCreated SubscriptionState = "created" // SubscriptionRenewed: the conversation's subscription with these // arguments, renewed. SubscriptionRenewed SubscriptionState = "renewed" // SubscriptionNative: the client subscribes itself (MCP Events); the // block tells it what to subscribe to. SubscriptionNative SubscriptionState = "native" SubscriptionUnavailable SubscriptionState = "unavailable" // SubscriptionDisabled: the client is disabled. SubscriptionDisabled SubscriptionState = "disabled" )
What a Subscribe did.
type SubscriptionStatus ¶
type SubscriptionStatus struct {
ID string `json:"id"`
User string `json:"user"`
// Live: the subscription is the user's, to this event, and hasn't
// ended. One that names nothing reports false too.
Live bool `json:"live"`
// Connected: its conversation is reachable now (a stream, a wait, a
// connector or hook), and Via says how: "stream", "poll", "hooks" or
// "webhook".
Connected bool `json:"connected"`
Via string `json:"via,omitempty"`
}
SubscriptionStatus is one subscription's status (StatusOf).
type TokenError ¶
type TokenError struct {
Reason string // one of the Reason constants
Past time.Duration // for ReasonExpired: how long past its expiry it was
}
TokenError is why a bearer token was refused: an app's verifier returns one for a token it refuses. It unwraps to auth.ErrInvalidToken, so a verifier for the MCP SDK's middleware or RequireBearer can return it as it is.
func (*TokenError) Error ¶
func (e *TokenError) Error() string
func (*TokenError) Unwrap ¶
func (e *TokenError) Unwrap() error
type ToolCall ¶
type ToolCall struct {
// Request is go-sdk's request (nil under mcp-go, whose handler takes
// its own).
Request *mcp.CallToolRequest
// User is who Identify says is calling ("" for none, and always on a
// disabled client). It's Wakeshift's view of the caller: your own
// authorization rests on your own verified credential, never on it.
User string
// Agent is the agent the app acts for (Identity.Agent), if any.
Agent *Agent
// Tool is the tool being called.
Tool string
// Native: the client subscribes to the app's events itself (MCP
// Events). Subscribe then makes no conversation subscription, and the
// block tells it what to subscribe to.
Native bool
// NativeConversation is a native client's conversation, when it names
// one, else "".
NativeConversation string
// Recognized is what Wakeshift recognized the agent's program as: nil
// until a Subscribe or ResolveSession.
Recognized *Recognized
// contains filtered or unexported fields
}
ToolCall is one call of a tool that subscribes: who's calling, and the conversation event.Subscribe subscribes. Printing or logging it never shows the request or the session.
func ToolCallFrom ¶
ToolCallFrom is the call of a tool that subscribes that ctx belongs to: for a tool named in AttachOptions.Wrap or WrapFunc (its handler's ctx), or code its handler calls. nil outside one; event.Subscribe with a nil call returns CodeNoCall, except on a disabled client.
func (*ToolCall) ResolveSession ¶
func (c *ToolCall) ResolveSession(ctx context.Context) (SessionKey, error)
ResolveSession finds or starts the calling conversation's session without subscribing it to anything (it doesn't make the conversation wakeable), and returns it. It returns "", with no request to Wakeshift, when nothing names the conversation: no session_key, no conversation_id and no conversation in the call's _meta (a Codex thread). Without a user (identify's), only the session_key names it: a conversation ID alone returns "" too. On a disabled client it returns CodeDisabled.
func (*ToolCall) Session ¶
func (c *ToolCall) Session() SessionKey
Session is the conversation's session key, set once Wakeshift resolved the conversation (a Subscribe that reached it, or ResolveSession): "" until then, and never the raw session_key argument, which anyone can make up. It prints as [redacted]; string(call.Session()) is the key.
type ToolHandler ¶
type ToolHandler[In, Out any] func(ctx context.Context, call *ToolCall, in In) (*mcp.CallToolResult, Out, error)
ToolHandler is a tool that subscribes: go-sdk's mcp.ToolHandlerFor with the call (*ToolCall) after ctx, so an existing handler moves over unchanged. The input is your own type: Wakeshift's arguments never reach it.
type ToolOption ¶
type ToolOption func(*toolOptions)
ToolOption is an option of a tool that subscribes: Subscribes.
func Subscribes ¶
func Subscribes(events ...Subscribable) ToolOption
Subscribes names the events a tool subscribes the calling conversation to (with event.Subscribe). tools/list then tells the agent the tool is how the app wakes it on them, and a Subscribe to any other event returns CodeUndeclaredSubscribe. Subscribes() with no events is a tool that subscribes to nothing (it still gets held messages).
type UsageError ¶
type UsageError struct {
Code Code
Message string
// Issues are the arguments' or payload's problems, for bad_arguments.
Issues []Issue
}
UsageError is a mistake the SDK caught before sending anything: a bad option or value, an undeclared subscribe, a call on a disabled client, a call outside a tool call or after it returned, a failed identify. Its message says what failed, the fix in one clause, and a docs anchor.
func (*UsageError) Error ¶
func (e *UsageError) Error() string
type WatchOption ¶
type WatchOption interface {
// contains filtered or unexported methods
}
WatchOption shapes a Watch: Every, Timeout, MaxErrors, FinalIf, WithID and To (a personal event's recipient).
func Every ¶
func Every(d time.Duration) WatchOption
Every is how long a Watch waits between checks (default 30 seconds, at least 1 second). After n check errors in a row it waits longer: Every·2ⁿ, up to 5 minutes (or Every, if that's longer).
func FinalIf ¶
func FinalIf(f func(error) bool) WatchOption
FinalIf marks a check error final: one it reports true for stops the Watch at once (a job that no longer exists, a revoked credential).
func MaxErrors ¶
func MaxErrors(n int) WatchOption
MaxErrors is how many check errors in a row stop a Watch (default 5).
func Timeout ¶
func Timeout(d time.Duration) WatchOption
Timeout is how long a Watch runs at most, checks and emit retries included (default 1 hour). It must be at least Every.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
adapt
Package adapt is what wakeshift shares with its adapters for other MCP libraries (wakeshift/mcpgo), without making it wakeshift's public API: a tool call's request, a built-in tool and Wakeshift's block in a form no MCP library owns, the helpers both sides use on tool schemas and results, and Impl, wakeshift's side, which an adapter calls directly.
|
Package adapt is what wakeshift shares with its adapters for other MCP libraries (wakeshift/mcpgo), without making it wakeshift's public API: a tool call's request, a built-in tool and Wakeshift's block in a form no MCP library owns, the helpers both sides use on tool schemas and results, and Impl, wakeshift's side, which an adapter calls directly. |
|
appkey
Package appkey reads and writes app keys: the app's Ed25519 private key, as the console shows it once.
|
Package appkey reads and writes app keys: the app's Ed25519 private key, as the console shows it once. |
|
framing
Package framing is how every Wakeshift message is put in front of a model: a short plain preface saying it comes from outside the conversation and isn't the user's instruction, and how to answer, then each message in a tag
|
Package framing is how every Wakeshift message is put in front of a model: a short plain preface saying it comes from outside the conversation and isn't the user's instruction, and how to answer, then each message in a tag |
|
harnesses
Package harnesses is what Wakeshift's core knows about each agent harness: how to recognize it (the MCP clientInfo name it sends, else a _meta key or User-Agent token only it sends: Recognize), how its conversations are woken, how a tool result's beacon reaches its hook and is bound to the conversation, and what to tell its agent about installing Wakeshift's hooks (the install command and the harness's own trust step).
|
Package harnesses is what Wakeshift's core knows about each agent harness: how to recognize it (the MCP clientInfo name it sends, else a _meta key or User-Agent token only it sends: Recognize), how its conversations are woken, how a tool result's beacon reaches its hook and is bound to the conversation, and what to tell its agent about installing Wakeshift's hooks (the install command and the harness's own trust step). |
|
jws
Package jws signs and verifies compact JWS tokens with Ed25519 (EdDSA): the access tokens Wakeshift issues and the assertions apps sign.
|
Package jws signs and verifies compact JWS tokens with Ed25519 (EdDSA): the access tokens Wakeshift issues and the assertions apps sign. |
|
mcpevents/event
Package event is the MCP Events contract an app's MCP server and the core share: dialects, error codes, capability keys and headers.
|
Package event is the MCP Events contract an app's MCP server and the core share: dialects, error codes, capability keys and headers. |
|
Package mcpgo attaches Wakeshift to an MCP server built with github.com/mark3labs/mcp-go, as wakeshift.Attach and wakeshift.AddTool do for the official Go SDK.
|
Package mcpgo attaches Wakeshift to an MCP server built with github.com/mark3labs/mcp-go, as wakeshift.Attach and wakeshift.AddTool do for the official Go SDK. |
|
Package wakeshifttest helps unit-test code that uses wakeshift, offline.
|
Package wakeshifttest helps unit-test code that uses wakeshift, offline. |