Documentation
¶
Overview ¶
Package appkit is the SDK for apps built on Wakeshift (Agent Chat, the games, and anyone else's).
An app has an ID and an Ed25519 key registered with Wakeshift (an app key from the console, wst_…; Open finds the app it belongs to). With them it:
- publishes its manifest (what it may do) and proves who it is with short-lived signed assertions;
- identifies its own users, with its own sign-in, in workspaces it owns (Workspace, AddAgent); RequireBearer checks the tokens MCP clients send;
- defines events (DefineEvent) and attaches them to its MCP server (Attach, for the official Go SDK; package appkit/mcpgo for one built with mark3labs/mcp-go), so an agent that subscribes wakes when the app emits one;
- subscribes the conversation calling one of its own tools, from a tool wrapped by Events (DefinedEvent.Subscribe), and emits to the conversations it stored (Emit with ToSubscription);
- acts for a user's agent (ActAs), so a wrapped tool's subscriptions are the agent's, inside the grant the app's manifest asks for.
Its calls are the TypeScript and Python SDKs' (@wakeshift/sdk, wakeshift), in Go's shape. Unlike them, only Open reads WAKESHIFT_CORE and defaults to DefaultCore.
Index ¶
- Constants
- Variables
- func CloudLogging(groups []string, a slog.Attr) slog.Attr
- func CodexThread(meta map[string]any) string
- func Events[In WakeInput, Out any](at *Attachment, ...) mcp.ToolHandlerFor[In, Out]
- func HarnessAgent(client string) string
- func IsCode(err error, code string) bool
- func LogMCP(h http.Handler) http.Handler
- func NewLogHandler(w io.Writer) slog.Handler
- func Notifies(description string, opts ...NotifyOption) string
- func ParseKey(s string) (ed25519.PrivateKey, error)
- func RequireBearer(verify auth.TokenVerifier, metadataURL string) func(http.Handler) http.Handler
- type APIError
- type Agent
- type AgentScope
- type App
- func (a *App) ActAs(ctx context.Context, workspace, agent string) (*Agent, error)
- func (a *App) AddAgent(ctx context.Context, workspace, agent, displayName string) (string, error)
- func (a *App) Attach(srv *mcp.Server, opts AttachOptions) *Attachment
- func (a *App) CheckAgent(ctx context.Context, workspace, agent string) error
- func (a *App) EndEventSubscription(ctx context.Context, user, id string) (bool, error)
- func (a *App) EventSubscriptions(ctx context.Context, user string) ([]EventSubscription, error)
- func (a *App) ForgetUser(ctx context.Context, user string) (bool, error)
- func (a *App) Info(ctx context.Context) (AppInfo, error)
- func (a *App) PublishManifest(ctx context.Context, m Manifest) error
- func (a *App) RevokePublishURL(ctx context.Context, id string) error
- func (a *App) Workspace(ctx context.Context, externalID, name string) (string, error)
- type AppInfo
- type AttachOptions
- type Attachment
- type DefinedEvent
- func (e *DefinedEvent[A, P]) Emit(ctx context.Context, args A, payload P, opts ...EmitOption) (Emitted, error)
- func (e *DefinedEvent[A, P]) End(ctx context.Context, user, id string) (bool, error)
- func (e *DefinedEvent[A, P]) Name() string
- func (e *DefinedEvent[A, P]) PublishURL(ctx context.Context, args A, opts ...EmitOption) (PublishURL, error)
- func (e *DefinedEvent[A, P]) Status(ctx context.Context, args A, opts ...EmitOption) (EventStatus, error)
- func (e *DefinedEvent[A, P]) StatusOf(ctx context.Context, subs ...Recipient) ([]EventSubscriptionStatus, error)
- func (e *DefinedEvent[A, P]) Subscribe(ctx context.Context, call *ToolCall, args A, opts ...SubscribeOption) (Subscription, error)
- func (e *DefinedEvent[A, P]) Unsubscribe(ctx context.Context, call *ToolCall, args A) (bool, error)
- type EmitOption
- type Emitted
- type EventDef
- type EventStatus
- type EventSubscription
- type EventSubscriptionStatus
- type EventsOption
- type EventsOptions
- type Identity
- type Manifest
- type ManifestEvent
- type NotifyOption
- type PublishURL
- type RateLimiter
- type Recipient
- type Recognized
- type ScopeEvent
- type SubscribeOption
- type SubscribedEvent
- type Subscriber
- type Subscription
- type TokenError
- type Tool
- type ToolCall
- type Tools
- type Wait
- type WakeArgs
- type WakeInput
- type WakeLimit
- type WakeOutput
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 ( SessionArg = harnesses.SessionArg // session_key HarnessArg = harnesses.HarnessArg // harness ConversationArg = harnesses.ConversationArg // conversation_id )
The arguments WakeArgs adds to a tool.
const ( ViaStream = "stream" // a stream held open (a lines stream such as Cursor's background command, an SSE or WebSocket client) ViaPoll = "poll" // long polls, waits (Claude Code's Monitor, Antigravity's background command) or a wait tool, within the last minute ViaHooks = "hooks" // Wakeshift's hooks or connector on the user's machine ViaWebhook = "webhook" // a client's own MCP Events webhook (a native subscription) )
How a conversation is connected (EventStatus.Via, EventSubscriptionStatus.Via).
const ( SubscribeEventsTool = "subscribe_events" UnsubscribeEventsTool = "unsubscribe_events" ListSubscriptionsTool = "list_subscriptions" )
The names of Attach's own tools.
const ConnectorMetaKey = "wakeshift/connector"
ConnectorMetaKey is where a tool result carries a connector beacon.
const DefaultCore = "https://app.wakeshift.ai"
DefaultCore is Wakeshift's production core: where a key goes unless WAKESHIFT_CORE (or Open's core) says otherwise. A wst_test_ key has no default: it came from another console.
const MaxStatusSubscriptions = 1000
MaxStatusSubscriptions is the most subscriptions one StatusOf reads.
const TaskIDPrefix = "wkt1_"
TaskIDPrefix starts every Wakeshift task ID (waittask.Prefix): tasks/get and tasks/cancel for any other ID aren't Wakeshift's.
const (
TasksExtension = "io.modelcontextprotocol/tasks"
)
The MCP tasks extension's capability key, and the protocol revision a request must be on for Wrap to serve the wait tool.
const WaitTool = harnesses.WaitTool
WaitTool is the name of Wakeshift's wait tool (harnesses.WaitTool).
const WakeshiftField = adapt.WakeshiftField
WakeshiftField is the structuredContent field a wrapped tool's structured result carries Wakeshift's block in (without a beacon line), for hosts that show the model only structuredContent. The three SDKs use the same name.
Variables ¶
var ( // ErrNoCall: the ToolCall wasn't made by Events (a zero ToolCall, or // one built by hand). Only a wrapped tool's handler gets a working one. ErrNoCall = errors.New("appkit: this ToolCall wasn't made by appkit.Events: subscribe only from a wrapped tool's handler") // ErrCallEnded: the handler that got the ToolCall has returned. ErrCallEnded = errors.New("appkit: the tool call has ended: subscribe before the handler returns") )
Errors from a *ToolCall used where it can't be.
var ErrIDReused = errors.New("wakeshift: id_reused")
ErrIDReused is what errors.Is matches for an Emit whose ID was used within the last day for a different emit (another event, arguments, recipients or payload): an *APIError with Status 409 and Code id_reused. Nothing was sent. A retry of the same emit isn't refused: it returns the first emit's result, with Emitted.Duplicate set.
Functions ¶
func CloudLogging ¶
CloudLogging is a slog ReplaceAttr that renames level and msg to Cloud Logging's severity and message (and WARN to WARNING).
func CodexThread ¶
CodexThread is the Codex thread an MCP tool call came from, if any, from the call's _meta: Codex sends x-codex-turn-metadata.thread_id (0.160+), or threadId (earlier). A turn another harness runs in Codex's app-server (OpenClaw marks it x-codex-turn-metadata.thread_source "openclaw") isn't a Codex thread's: its conversation is that harness's, which Codex's connector doesn't wake, so it's "".
func Events ¶ added in v0.4.0
func Events[In WakeInput, Out any](at *Attachment, h func(context.Context, *ToolCall, In) (*mcp.CallToolResult, Out, error), opts ...EventsOption) mcp.ToolHandlerFor[In, Out]
Events wraps a tool handler for mcp.AddTool so it gets a *ToolCall, and its reply gets Wakeshift's block. Add the tool after Attach, on the server passed to it; register Attach after the server's own receiving middleware, so its block stays last.
Subscribes declares the events the handler subscribes to: tools/list then says the tool is how the app notifies the agent of them, and a Subscribe to an event the tool doesn't declare warns (from the next release, it returns an error).
mcp.AddTool(srv, &mcp.Tool{Name: "watch_build", Description: "Watch a build until it finishes."},
appkit.Events(attached, watchBuild, appkit.Subscribes(buildFinished)))
In must embed WakeArgs. A structured result (Out not any, or a CallToolResult with StructuredContent an object) carries the block's text in its wakeshift field too, and tools/list names the field in the tool's output schema; embedding WakeOutput in Out declares it in the type.
func HarnessAgent ¶
HarnessAgent is the agent ID a client is named by: its harness's ID ("copilot-cli" → copilot, "Claude Code" → claude-code), as Wakeshift names it, else its name as an ID (lowercase letters, digits and dashes; "agent" if nothing's left): for naming the agent an app adds for an MCP client (AddAgent).
func LogMCP ¶
LogMCP wraps an MCP endpoint to log each request: the JSON-RPC method (and tool name), the client, the status, how long it took, how much it sent, and what kind of message the response began with ("result", "error", or a server-to-client method). Never the content: tool results can hold stream links, which are credentials. A request still open after a while is logged then too, so one that never finishes shows what it's waiting on.
func NewLogHandler ¶
NewLogHandler returns a JSON slog handler that writes Cloud Logging's field names (severity, message), so a server's errors show up as errors in Cloud Run's logs rather than at the default severity.
func Notifies ¶ added in v0.7.0
func Notifies(description string, opts ...NotifyOption) string
Notifies is a tool's description, for a tool that subscribes the calling conversation (Subscribe in its Events handler), with sentences after it saying that the tool is how the app notifies the agent (when, if given: NotifyWhen), that the app delivers its notifications through Wakeshift, and what the result may ask (the same sentences in every SDK). tools/list names the app as the console has it (GET /app; Attach's middleware); NotifyApp overrides that, and with neither the sentence says "this app". Agents set Wakeshift's part of the result aside as unrequested unless the tool's own description says so (wakebench's realistic tier, November 2026). Use it only for tools that subscribe: the sentence says so.
It's an optional override, for wording the sentence yourself: declaring the tool's events with Subscribes writes it for you, from the events' own descriptions, and a description that already has a Notifies sentence gets no second one.
mcp.AddTool(srv, &mcp.Tool{Name: "watch_build", Description: appkit.Notifies("Watch a build until it finishes.", appkit.NotifyWhen("a build finishes"))}, appkit.Events(attached, watchBuild, appkit.Subscribes(buildFinished)))
func ParseKey ¶
func ParseKey(s string) (ed25519.PrivateKey, error)
ParseKey reads an app's Ed25519 private key: an app key from the console (wst_…, either format, see Open), or base64 (standard or URL) of a 32-byte seed or a 64-byte key.
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 string
Message string
// Reason, for some errors, is a category (an MCP Events callback that
// failed verification: challenge_failed, http_4xx…).
Reason string
// contains filtered or unexported fields
}
APIError is an error response from Wakeshift, or a mistake the SDK catches before asking it (an emit without a recipient, another app's event), with the code and status Wakeshift gives for the same mistake. A request that got no answer at all (a wrong core, a network problem, the HTTP client's timeout) is one with Status 0 and the code unreachable, which unwraps to the transport's error.
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.
func (*Agent) Request ¶ added in v0.4.0
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.
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 App ¶
type App struct {
ID string
Key ed25519.PrivateKey
Core string // Wakeshift's base URL, e.g. https://app.wakeshift.ai
MCPURL string // this app's MCP endpoint (the resource its tokens are for)
HTTP *http.Client // default: one with a 20s timeout
// contains filtered or unexported fields
}
App is an app's identity and its connection to Wakeshift.
func Open ¶
Open returns the App for an app key from the console, either format, with its ID: from the key, if it names the app, or else from Wakeshift (GET /api/apps/v1/app, once). core is Wakeshift's base URL; "" reads WAKESHIFT_CORE, then falls back to DefaultCore, except for a wst_test_ key, which needs one of the two.
func (*App) 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 (*App) AddAgent ¶
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 (*App) Attach ¶ added in v0.2.0
func (a *App) Attach(srv *mcp.Server, opts AttachOptions) *Attachment
Attach attaches Wakeshift to the app's MCP server: the one call that connects the two. Today it serves MCP Events and the event tools, so every client can subscribe to the app's event types (define them first, with DefineEvent); Wrap puts it in front of the MCP endpoint's handler.
- Clients that speak MCP Events (ChatGPT) subscribe natively: Wrap advertises the events capability (server/discover and initialize, under both the draft's extension key and the top-level key ChatGPT reads), answers events/list with the event types, and passes events/subscribe and events/unsubscribe to Wakeshift, which verifies the client's callback and POSTs occurrences to it, signed, in order (docs/mcp-events-bridge.md). It speaks the revision event.Revision names, in two dialects chosen per request by the client's clientInfo (or User-Agent): ChatGPT's and the draft's. An Mcp-Name header, when present, must match params.name.
- Every other client subscribes with the subscribe_events tool, which Attach adds to srv (tools/list hides it from native clients), and Wakeshift wakes it the way its harness can be woken.
- Every client can list its subscriptions (list_subscriptions) and stop one (unsubscribe_events): a headless app's users have no other way.
AttachOptions.Tools picks which of the three tools it adds (all three by default), and Tools.Wait adds Wakeshift's wait tool for Claude Code (off by default).
Call it once per server, after the last DefineEvent (with none defined it panics: it would serve nothing; calling it again replaces the tools, as the MCP SDK's AddTool does), and after the server's own receiving middleware: its middleware then runs last on a tool's result, so the block a wrapped tool's reply gets (Events) stays last. Add wrapped tools after it. Each event type's Authorize runs before any subscription. The tools' wording is fixed, and the TypeScript SDK's is the same (sdk/typescript/test/event-tools.json). Wrap the MCP handler after the endpoint's authentication:
attached := app.Attach(srv, appkit.AttachOptions{
Identify: func(_ context.Context, ti *auth.TokenInfo) (appkit.Identity, error) {
return appkit.Identity{User: ti.UserID}, nil
},
})
h := mcp.NewStreamableHTTPHandler(…, &mcp.StreamableHTTPOptions{Stateless: true})
mux.Handle("/mcp", requireAuth(attached.Wrap(h)))
func (*App) CheckAgent ¶ added in v0.4.0
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 (*App) EndEventSubscription ¶
EndEventSubscription ends one of a user's subscriptions by its ID (EventSubscriptions'), wherever it delivers; a webhook's receiver is told. It reports whether one ended.
func (*App) EventSubscriptions ¶
EventSubscriptions lists a user's live subscriptions to the app's event types (user: the app's ID for them).
func (*App) 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.
func (*App) 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 (*App) RevokePublishURL ¶
RevokePublishURL stops a publish URL working.
type AppInfo ¶
type AppInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Key struct {
KeyID string `json:"key_id"` // the console's key ID
Name string `json:"name"`
} `json:"key"`
}
AppInfo is which app and key signed a request, as Wakeshift says.
type AttachOptions ¶ added in v0.2.0
type AttachOptions struct {
// Identify tells who's behind a request, from the endpoint's
// authentication (it isn't called for a request with none). An error
// counts as no user. Typically the app's own ID for the user its token
// names (the TokenInfo's UserID), and the agent from ActAs for an app
// acting for its agents. Nil: no request has a user.
Identify func(context.Context, *auth.TokenInfo) (Identity, error)
// Tools picks which of Attach's own tools it adds. The zero value is
// the default: subscribe_events, unsubscribe_events and
// list_subscriptions, and not the wait tool. Turn the wait tool on with
// Tools: appkit.Tools{Wait: appkit.Wait{Enabled: true}}, and leave one
// of the others out with, e.g., Tools: appkit.Tools{Subscribe:
// appkit.Tool{Disabled: true}}.
Tools Tools
// Events configures the event features.
Events EventsOptions
}
AttachOptions configure Attach.
type Attachment ¶ added in v0.2.0
type Attachment struct {
// contains filtered or unexported fields
}
Attachment is Wakeshift attached to an MCP server (Attach).
func (*Attachment) Wrap ¶ added in v0.2.0
func (at *Attachment) Wrap(next http.Handler) http.Handler
Wrap puts Wakeshift in front of the MCP endpoint's handler, after the endpoint's authentication: MCP Events' methods and capability, and with AttachOptions.Tools.Wait, for clients on protocol 2026-07-28 that take MCP tasks, Wakeshift's wait tool and the tasks it answers with (tasks.go).
type DefinedEvent ¶
type DefinedEvent[A, P any] struct { // contains filtered or unexported fields }
DefinedEvent is one of the app's event types (DefineEvent): Emit sends an occurrence.
func DefineEvent ¶
DefineEvent defines one of the app's event types: 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 (PublishManifest sends it at once).
func (*DefinedEvent[A, P]) Emit ¶
func (e *DefinedEvent[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). The payload is checked against the event's schema. 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.
func (*DefinedEvent[A, P]) End ¶
End ends one of user's subscriptions to the app's events by its ID (from Subscribe or EventSubscriptions), wherever it delivers, reporting whether one ended. It's App.EndEventSubscription.
func (*DefinedEvent[A, P]) Name ¶
func (e *DefinedEvent[A, P]) Name() string
Name is the event type's name.
func (*DefinedEvent[A, P]) PublishURL ¶
func (e *DefinedEvent[A, P]) PublishURL(ctx context.Context, args A, opts ...EmitOption) (PublishURL, error)
PublishURL makes a 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; the agent reads the event's name and the start of the payload, since Text doesn't run. Anyone with the URL can emit until App.RevokePublishURL.
func (*DefinedEvent[A, P]) Status ¶ added in v0.4.0
func (e *DefinedEvent[A, P]) Status(ctx context.Context, args A, opts ...EmitOption) (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.
func (*DefinedEvent[A, P]) StatusOf ¶ added in v0.4.0
func (e *DefinedEvent[A, P]) StatusOf(ctx context.Context, subs ...Recipient) ([]EventSubscriptionStatus, error)
StatusOf reads subscriptions to this event by ID, each with the user Subscribe returned it for (Recipient's User and Subscription), up to MaxStatusSubscriptions at once: whether each is live and its conversation connected. It only reads.
func (*DefinedEvent[A, P]) Subscribe ¶
func (e *DefinedEvent[A, P]) Subscribe(ctx context.Context, call *ToolCall, args A, opts ...SubscribeOption) (Subscription, error)
Subscribe subscribes the conversation calling a wrapped tool (call: the handler's) to this event with args, or renews its subscription. The tool's reply then carries what the conversation needs to be woken (one block for the call, however many subscribes it makes), and if the call fails, the subscription is ended. For a native caller (call.Native) nothing is made: the block tells it to subscribe to the event itself. Your tool decides who may: Authorize isn't consulted. A personal event needs a user (Identify's). It's the TypeScript SDK's call.subscribe.
func (*DefinedEvent[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.
type EmitOption ¶
type EmitOption func(*emitOptions)
EmitOption shapes an Emit.
func To ¶
func To(users ...string) EmitOption
To sends a personal event's occurrence to users (the app's IDs for them): only their subscriptions get it. A personal event needs at least one recipient (To, ToSubscription or ToNative), and any other refuses them. Repeatable, and mixable with the others in one Emit.
func ToNative ¶ added in v0.4.0
func ToNative(users ...string) EmitOption
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 ¶ added in v0.4.0
func ToSubscription(user, id string) EmitOption
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.
func WithID ¶
func WithID(id string) EmitOption
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 with an error that errors.Is ErrIDReused (409 id_reused), and nothing is sent: give each occurrence its own ID.
type Emitted ¶
type Emitted struct {
// Matched is how many conversations it reached, each woken now or as
// soon as its agent can take it, webhooks included (0: nobody's
// subscribed).
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 (nothing new was sent).
Duplicate bool `json:"duplicate"`
// Unmatched are the user and native recipients with no live
// subscription it reached, whether it names one or many.
Unmatched []Recipient `json:"-"`
// Ended are the subscription recipients that are no longer live (or
// aren't that user's, or this event's): forget them. A duplicate
// reports the first emit's.
Ended []Recipient `json:"-"`
// TextTrimmed: the text was over 1000 bytes, so Wakeshift trimmed it to
// 1000 (ending with "…") and sent the occurrence. The SDK logs a
// warning once per event.
TextTrimmed bool `json:"text_trimmed,omitempty"`
}
Emitted is what an Emit reached.
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 (framed by // Wakeshift as information from outside): from + ": " + text. Required. Text func(payload P, args A) string // Authorize says whether s may subscribe with these arguments (nil: // everyone). It runs before any subscription, native or bridged. Authorize func(ctx context.Context, s Subscriber, args A) bool // Personal: each subscription belongs to its subscriber (Identity.User), // and Emit sends an occurrence to one of them (To), so it may // carry that subscriber's own private view. Nothing in the arguments // names the subscriber: Wakeshift takes it from the subscriber's own // sign-in. Personal 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 (IDs, times, where it went). For // messages people wouldn't expect a third party to keep, such as chat // messages. One that isn't delivered expires as any other does. An // agent can't have it again after delivery: a replay skips it. 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 (Wakeshift's topics; see the // core's apps.EventType), 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, lowercase // a-z 0-9 . _ -), and an equality filter on the payload field of each // optional argument with the same name, added to Filter. A Filter // on the same field as an optional argument is refused. Topic string Filter map[string]string }
EventDef describes an event type: A is a subscription's arguments, 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; ArgsSchema and PayloadSchema replace them.
type EventStatus ¶ added in v0.4.0
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
// (ViaStream, ViaPoll, ViaHooks, ViaWebhook).
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 EventSubscriptionStatus ¶ added in v0.4.0
type EventSubscriptionStatus 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.
Connected bool `json:"connected"`
Via string `json:"via,omitempty"`
}
EventSubscriptionStatus is one event subscription's status (StatusOf).
type EventsOption ¶ added in v0.8.0
type EventsOption func(*eventsOptions)
EventsOption shapes Events (and mcpgo.Events).
func Subscribes ¶ added in v0.8.0
func Subscribes(events ...SubscribedEvent) EventsOption
Subscribes declares the events a wrapped tool subscribes the calling conversation to (with event.Subscribe). tools/list then adds a sentence to the tool's description saying the tool is how the app notifies the agent of them, in their own descriptions' words, and that the result may ask to start a listener and offer an install: agents set Wakeshift's part of a result aside as unrequested unless the tool's description says so. A Subscribe to an event the tool doesn't declare warns (from the next release, it returns an error). Subscribes() with no events declares that the tool subscribes to nothing.
mcp.AddTool(srv, &mcp.Tool{Name: "watch_build", Description: "Watch a build until it finishes."},
appkit.Events(attached, watchBuild, appkit.Subscribes(buildFinished)))
func ToolName ¶ added in v0.8.0
func ToolName(name string) EventsOption
ToolName names the tool Events wraps, as mcp.AddTool registers it, so tools/list finds it by name for Subscribes' sentence. go-sdk doesn't tell Events the name: without ToolName, tools/list finds the tool by the input schema go-sdk infers from its input type, which works while each subscribing tool has an input type of its own. Name the tool when tools share one.
mcp.AddTool(srv, &mcp.Tool{Name: "join", Description: "Join a game."},
appkit.Events(attached, join, appkit.Subscribes(updates), appkit.ToolName("join")))
type EventsOptions ¶
type EventsOptions struct {
// Native, if set, is asked first whether a wrapped tool's call comes
// from a client that subscribes to the app's events itself
// (ToolCall.Native), for callers the SDK can't tell (an app's own house
// agents). False leaves it to the SDK's own checks.
Native func(ctx context.Context, req *mcp.CallToolRequest) bool
}
EventsOptions configure Attach's event features.
type Identity ¶ added in v0.2.0
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, for the user's
// workspace and agent), if any: every call for the request is then the
// agent's, with its token, and the user is Agent.User(). A wrapped
// tool's subscriptions are the agent's sessions'.
Agent *Agent
// Client is the MCP client's name, for a request that doesn't carry
// one: a stateless server never sees initialize, so the app passes the
// name it knows from its own sign-in (an OAuth registration's
// client_name, say). Wakeshift reads it to tell which program the agent
// runs in, and whether the client subscribes to events itself. A name
// the request carries (initialize's, or its _meta's) wins. Leave it ""
// for a caller that must have no name.
Client string
}
Identity is who's behind a request to the app's MCP endpoint, as the app knows them (AttachOptions.Identify).
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
// (App.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"`
}
ManifestEvent is an event type in the manifest (see the core's apps.EventType). DefineEvent makes these, and the manifest lists them.
type NotifyOption ¶ added in v0.7.0
type NotifyOption func(*notifyOptions)
NotifyOption is an option of Notifies.
func NotifyApp ¶ added in v0.7.0
func NotifyApp(name string) NotifyOption
NotifyApp names the app in Notifies' sentence (default: as the console has it, filled in by tools/list).
func NotifyWhen ¶ added in v0.7.0
func NotifyWhen(when string) NotifyOption
NotifyWhen says when the tool notifies, e.g. "a build finishes".
type PublishURL ¶
type PublishURL struct {
ID string `json:"id"`
Event string `json:"event"`
URL string `json:"url"`
}
PublishURL is a capability URL that emits one event (DefinedEvent.PublishURL: a POST's body is its payload).
type RateLimiter ¶
type RateLimiter struct {
// ProxyHops is how many trusted proxies are in front, each appending to
// X-Forwarded-For (0: the connection's address).
ProxyHops int
// contains filtered or unexported fields
}
RateLimiter allows max requests per window from each client address, in memory (per instance): an IPv6 address counts as its /64, X-Forwarded-For is read only as the trusted proxies wrote it, and the addresses tracked at once are capped (past the cap, a new address is refused until old ones expire). For an app's own unauthenticated endpoints, such as OAuth client registration.
func NewRateLimiter ¶
func NewRateLimiter(max int, window time.Duration, proxyHops int) *RateLimiter
NewRateLimiter allows max requests per window from each address.
type Recipient ¶ added in v0.4.0
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 Recognized ¶ added in v0.5.0
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 ScopeEvent ¶
type SubscribeOption ¶ added in v0.4.0
type SubscribeOption func(*subscribeOptions)
SubscribeOption shapes a Subscribe.
func Label ¶ added in v0.4.0
func Label(l string) SubscribeOption
Label names a new session (agent@label), for an app acting for its agents.
func Reason ¶ added in v0.4.0
func Reason(r string) SubscribeOption
Reason says why the app subscribes the conversation, shown in the console (at most 200 characters).
func TTL ¶ added in v0.4.0
func TTL(d time.Duration) SubscribeOption
TTL ends the subscription after this long without a delivery or a fresh subscribe (default 30 days).
type SubscribedEvent ¶ added in v0.8.0
type SubscribedEvent interface {
// contains filtered or unexported methods
}
SubscribedEvent is one of the app's events, as Subscribes takes it: every *DefinedEvent is one.
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 string
// Native: subscribing natively (MCP Events), not through subscribe_events.
Native bool
}
Subscriber is who's subscribing: what Authorize decides on.
type Subscription ¶
type Subscription struct {
ID string `json:"id"`
User string `json:"user"`
// Created is false for a renewal.
Created bool `json:"created"`
// Session is the conversation's session.
Session string `json:"session"`
// Recognized is what Wakeshift recognized the agent's program as.
Recognized Recognized `json:"recognized"`
// Native: the caller subscribes itself (ToolCall.Native); nothing was
// made, ID is "", and the block tells it what to subscribe to.
Native bool `json:"native"`
}
Subscription is the calling conversation's subscription, made or renewed by Subscribe. ID and User address it later: an Emit's ToSubscription(User, ID), or End(ctx, User, ID).
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 Tool ¶ added in v0.9.0
type Tool struct {
Disabled bool
}
Tool is one of Attach's own tools that it adds unless disabled.
type ToolCall ¶ added in v0.4.0
type ToolCall struct {
// Request is the MCP request.
Request *mcp.CallToolRequest
// User is who AttachOptions.Identify says is calling ("" for none).
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:
// ChatGPT, the house agents). 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 (ChatGPT's _meta["openai/session"]), else "".
NativeConversation string
// Session is the session_key passed; after Subscribe or
// ResolveSession, the conversation's session.
Session 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 wrapped tool (Events): who's calling, and the calls that subscribe the calling conversation.
func ToolCallFrom ¶ added in v0.4.0
ToolCallFrom is the wrapped tool's call that ctx belongs to (Events), for receiving middleware the server added before Attach, which runs inside Attach's: nil for a call of a tool Events didn't wrap, or until its handler starts. Once the handler has returned, its Session is the conversation's session if it subscribed or resolved one.
type Tools ¶ added in v0.9.0
type Tools struct {
// Wait is Wakeshift's wait tool, wakeshift_wait: off unless enabled.
Wait Wait
// Subscribe is subscribe_events, for clients that don't speak MCP
// Events (tools/list hides it from those that do).
Subscribe Tool
// List is list_subscriptions. Disable it, or Unsubscribe, only if your
// own tools let a person see and stop their subscriptions.
List Tool
// Unsubscribe is unsubscribe_events.
Unsubscribe Tool
}
Tools picks which of Attach's own tools it adds (AttachOptions.Tools). Its zero value is the default: subscribe_events, unsubscribe_events and list_subscriptions on, and the wait tool off. So the three that are on by default have a Disabled field, and the wait tool, off by default, an Enabled one: leaving a field out always means the default.
type Wait ¶ added in v0.9.0
type Wait struct {
Enabled bool
}
Wait is the wait tool's options (Tools.Wait): Wakeshift's wait tool, wakeshift_wait, Claude Code's wake path with nothing installed, where its client takes MCP tasks (protocol 2026-07-28; tasks.go). Off by default: Wrap serves no wait tool, and Claude Code is woken by its plugin or, after a no, a background Monitor, as every other server's is. Enabled, a waiting conversation's Claude Code holds a request to the endpoint (tasks/get, about 20 seconds) and sends the next about a second later, for as long as it waits: give the endpoint a write timeout of at least 30 seconds.
type WakeArgs ¶ added in v0.4.0
type WakeArgs struct {
SessionKey string `` /* 203-byte string literal not displayed */
Harness string `` /* 305-byte string literal not displayed */
ConversationID string "" /* 252-byte string literal not displayed */
}
WakeArgs are the arguments a wrapped tool takes so Wakeshift can find the calling conversation: embed it in the tool's input (Events requires it).
type WakeInput ¶ added in v0.4.0
type WakeInput interface {
// contains filtered or unexported methods
}
WakeInput is a wrapped tool's input: a struct that embeds WakeArgs (only WakeArgs has the method, so nothing else satisfies it).
type WakeOutput ¶ added in v0.4.0
type WakeOutput struct {
Wakeshift string `json:"wakeshift,omitempty" jsonschema:"What Wakeshift adds for this conversation: how it's woken by this app's events"`
}
WakeOutput, embedded in a wrapped tool's output, declares its wakeshift field in the type itself. It's optional: every structured result of a wrapped tool gets the block's text in wakeshift (Events), and tools/list names it in the tool's output schema. The block stays in the content as well.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
adapt
Package adapt is what appkit shares with its adapters for other MCP libraries (appkit/mcpgo), without making it appkit'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, appkit's side, which an adapter asserts to the interface it needs (with appkit's own types in it, which this package can't name).
|
Package adapt is what appkit shares with its adapters for other MCP libraries (appkit/mcpgo), without making it appkit'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, appkit's side, which an adapter asserts to the interface it needs (with appkit's own types in it, which this package can't name). |
|
Package mcpgo attaches Wakeshift to an MCP server built with github.com/mark3labs/mcp-go, as appkit's Attach and Events do for the official Go SDK (github.com/modelcontextprotocol/go-sdk).
|
Package mcpgo attaches Wakeshift to an MCP server built with github.com/mark3labs/mcp-go, as appkit's Attach and Events do for the official Go SDK (github.com/modelcontextprotocol/go-sdk). |