mcp

package
v1.15.2 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package mcp implements the Model Context Protocol JSON-RPC 2.0 transport that LLM clients (Claude Desktop, Cursor, Claude.ai web) call to discover and invoke wick connectors as tools.

Surface:

POST /mcp                                  — JSON-RPC requests
GET  /.well-known/oauth-protected-resource — auth metadata (RFC 9728)

Methods served (server-side, JSON-RPC 2.0):

initialize      — protocol handshake, capability negotiation
tools/list      — enumerate the caller's accessible connector ops
tools/call      — invoke one op, dispatching to connectors.Service.Execute
notifications/* — accepted as no-ops (we don't push from the server yet)

Auth model:

Static bearer (wick_pat_...) — PAT path, decoded via accesstoken.Service
OAuth opaque token           — OAuth path, decoded via oauth.Service
Anything else                — 401 with WWW-Authenticate pointing at
                                /.well-known/oauth-protected-resource

The auth middleware resolves a user_id and the user's filter-tag IDs onto the request context; everything below it (tools/list, tools/call) sees only the connectors that user can access.

Index

Constants

View Source
const InternalAgentUserID = "wick-agent-internal"

InternalAgentUserID is the id of the synthetic admin principal the per-boot internal token maps to. Agent spawns authenticate with that token, so this id shows up as the caller's user id for agent MCP calls that don't resolve a session owner — per-owner gates (data tables) treat it as an unrestricted system principal rather than a real user.

View Source
const ScopedTokenPrefix = "wick_sub_"

ScopedTokenPrefix marks tokens minted here. Distinct from the PAT prefix so resolveToken never routes one to the wrong validator.

Variables

This section is empty.

Functions

func SetAgentScopeResolver added in v1.2.9

func SetAgentScopeResolver(f AgentScopeResolver)

SetAgentScopeResolver wires the resolver both MCP entry points consult once the calling session is known. Set at boot; nil switches scoping off, which is also the state before boot reaches it.

func SetScopedTokenSecret added in v1.2.9

func SetScopedTokenSecret(f func() string)

SetScopedTokenSecret installs the signing key resolver. Called once at boot, next to clitoken.SetSecret.

Types

type AgentIdentity added in v1.0.0

type AgentIdentity struct {
	// User is the resolved wick user. nil = synthetic admin fallback.
	User *entity.User
	// TagIDs is the caller's filter-tag set, applied to connector
	// visibility exactly as it is for an HTTP-authed request. nil for the
	// admin fallback (no filtering).
	TagIDs []string
}

AgentIdentity is the principal an in-process agent tool call runs as. The zero value means "no resolved owner" and maps to the synthetic admin, matching the pre-per-user behaviour for ownerless spawns.

type AgentScopeResolver added in v1.2.9

type AgentScopeResolver func(ctx context.Context, sessionID string) connectors.AgentScope

AgentScopeResolver maps a session to the connector scope of the Agents-app agent it belongs to, or nil when the session is not an agent's (an ordinary session, a sub-agent of one, an unknown id).

type AuthMiddleware

type AuthMiddleware struct {
	// contains filtered or unexported fields
}

AuthMiddleware extracts the Authorization: Bearer header, routes the token to the right validator (PAT vs OAuth), loads the user record + filter-tag IDs, and stamps both onto the request context using login.WithUser so downstream code reads identity exactly the way it does for cookie-authed requests.

Unauth requests get a 401 with WWW-Authenticate pointing at the resource-metadata document (RFC 9728), so spec-compliant MCP clients can discover the OAuth server and run the auth dance.

func NewAuthMiddleware

func NewAuthMiddleware(tokens *accesstoken.Service, users userResolver, oauth oauthValidator, resourceMetaURL string) *AuthMiddleware

NewAuthMiddleware wires the bearer middleware. Pass nil oauth to run PAT-only (Phase B); attach later by replacing the field.

func (*AuthMiddleware) WithInternalToken added in v0.15.1

func (m *AuthMiddleware) WithInternalToken(token string) *AuthMiddleware

WithInternalToken sets the per-boot internal MCP secret agent spawns send as their Bearer token to reach the live MCP server over loopback.

func (*AuthMiddleware) WithScopedTokens added in v0.36.0

func (m *AuthMiddleware) WithScopedTokens(s *ScopedTokens) *AuthMiddleware

WithScopedTokens attaches the sub-agent token issuer.

func (*AuthMiddleware) Wrap

func (m *AuthMiddleware) Wrap(next http.Handler) http.Handler

Wrap returns the http.Handler middleware. Apply to /mcp.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler wires the MCP JSON-RPC surface — tools/list, tools/call, initialize. Bearer auth is applied by AuthMiddleware before this handler runs.

Tool surface uses a meta-tool pattern: three stable tools (wick_list, wick_search, wick_execute) let the LLM discover connectors at runtime. Adding/removing connectors never changes the cached tool list.

func NewHandler

func NewHandler(c *connectors.Service) *Handler

func (*Handler) AgentToolDescriptors added in v0.34.0

func (h *Handler) AgentToolDescriptors(ctx context.Context) []handlers.ToolDescriptor

AgentToolDescriptors returns the tool catalog the in-process agent may call, as the synthetic admin principal (full visibility). Kept for callers with no resolved owner; prefer AgentToolDescriptorsAs.

func (*Handler) AgentToolDescriptorsAs added in v1.0.0

func (h *Handler) AgentToolDescriptorsAs(ctx context.Context, id AgentIdentity) []handlers.ToolDescriptor

AgentToolDescriptorsAs returns the tool catalog visible to one principal. Tag filtering and the admin flag follow that principal, so an in-process agent sees exactly the tools its owning human may reach — the same answer the HTTP path gives for the same user.

func (*Handler) CallAgentTool added in v0.34.0

func (h *Handler) CallAgentTool(ctx context.Context, name string, args map[string]any, sessionID string) (string, bool)

CallAgentTool dispatches one tool call in-process and returns the tool result text + isError, reusing dispatchTool (identical routing to the HTTP transport). sessionID is stamped on the context so session-aware tools (ask_user, wick_session_*) resolve correctly — the same carrier the HTTP middleware uses, so neither path needs a header here.

func (*Handler) CallAgentToolAs added in v1.0.0

func (h *Handler) CallAgentToolAs(ctx context.Context, name string, args map[string]any, sessionID string, id AgentIdentity) (string, bool)

CallAgentToolAs dispatches one in-process tool call as a specific principal, so per-owner gates and tag filtering see the real human instead of a synthetic admin.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Handler) ServeStdio added in v0.5.1

func (h *Handler) ServeStdio(ctx context.Context, r io.Reader, w io.Writer)

ServeStdio runs the MCP JSON-RPC server over r/w for local clients (Claude Desktop, Cursor, etc.). Each line from r is one JSON-RPC message; the response is written as one JSON line to w.

No auth middleware — the caller pre-populates ctx with login.WithUser (typically a synthetic local admin) before calling. Logs go to stderr so the protocol stream stays clean.

func (*Handler) ServeStdioOS added in v0.5.1

func (h *Handler) ServeStdioOS(ctx context.Context)

ServeStdioOS is the process-level entrypoint: reads os.Stdin, writes os.Stdout. Thin wrapper around ServeStdio for production use.

func (*Handler) WithAccountQuota added in v1.2.9

func (h *Handler) WithAccountQuota(fn handlers.AccountQuotaFn) *Handler

WithAccountQuota wires the provider account quota reader — what wick_usage reports beside the token ledger. Optional: without it the tool omits the account section rather than guessing at one.

func (*Handler) WithAppURL added in v0.6.0

func (h *Handler) WithAppURL(get func() string) *Handler

func (*Handler) WithAskUser added in v0.9.0

func (h *Handler) WithAskUser(m askuser.Asker) *Handler

func (*Handler) WithAskUserPolicy added in v0.13.0

func (h *Handler) WithAskUserPolicy(fn func(sessionID string) (bool, string)) *Handler

func (*Handler) WithBuildInfo added in v0.5.1

func (h *Handler) WithBuildInfo(version, commit, buildTime string) *Handler

func (*Handler) WithDB added in v0.14.2

func (h *Handler) WithDB(db *gorm.DB) *Handler

func (*Handler) WithLayout added in v0.17.0

func (h *Handler) WithLayout(l agentconfig.Layout) *Handler

WithLayout wires the agents storage layout without a pool — stdio mode needs it for the session-scoped tools (wick_session_info, wick_set_title, wick_session_workspace) even though no agent pool runs in that process.

func (*Handler) WithPool added in v0.13.4

func (h *Handler) WithPool(p *agentpool.Pool, layout agentconfig.Layout) *Handler

func (*Handler) WithRefreshSession added in v0.16.13

func (h *Handler) WithRefreshSession(fn func(id string) error) *Handler

WithRefreshSession wires the registry-refresh callback used by wick_set_title to keep the dashboard's in-memory session cache in sync after the title is written to disk.

func (*Handler) WithSchedule added in v0.29.0

func (h *Handler) WithSchedule(s *schedule.Store) *Handler

WithSchedule wires the scheduled-message store that backs wick_schedule_message. nil (stdio/tests) disables the tool.

func (*Handler) WithWickRoot added in v0.6.0

func (h *Handler) WithWickRoot(root string) *Handler

type ScopedTokens added in v0.36.0

type ScopedTokens struct {
	// contains filtered or unexported fields
}

ScopedTokens issues short-lived bearer tokens that authenticate a spawned SUB-AGENT to the loopback MCP server as the human who triggered it, with an explicitly narrowed tag set.

Why this exists

Normal agent spawns authenticate with the per-boot internal token, which maps to a synthetic ADMIN principal. Admin bypasses tag filtering entirely. If a sub-agent were handed that same token, a profile's "allowed tags" would be decorative: the child would see every tool in the system regardless of what the profile said, and regardless of what its triggering user was allowed to reach.

So a sub-agent gets one of these instead. The token carries:

  • the REAL triggering user (so per-owner gates behave normally and the audit trail names a human, not a synthetic admin), and
  • a precomputed tag slice that is already the intersection of the user's tags with the profile's optional narrowing list.

Why they are signed rather than remembered

A grant used to live only in this process's map, which is right up to the moment the process is replaced. An agent outlives the daemon that spawned it — a graceful upgrade hands the socket to a successor while the old process finishes its turns — and the provider reads its MCP config exactly once, at spawn, so it cannot be handed a new token mid-run. A successor that never issued the token answers 401 to every tool call for the rest of that run.

Carrying the map across the handover (SaveHandoff/LoadHandoff) closed most of that, but not all of it: measured on 2026-09-22, the successor owned the socket at 08:59:08 and only adopted the predecessor's grants at 09:00:53 — 105 seconds of 401 for agents that were already running. A token minted by the outgoing process after its snapshot, or any restart that is not a handover (a crash, a systemd restart), is not carried at all.

So the grant travels INSIDE the token: an HS256 statement signed with the app's session secret, the same key and the same reasoning as a CLI token. Any generation of the daemon can verify one, there is nothing to hand over, and there is no window during boot where a valid token is not yet known. The map stays for two cases only — grants adopted from a predecessor that still minted the old opaque form, and installs with no session secret to sign with.

func NewScopedTokens added in v0.36.0

func NewScopedTokens() *ScopedTokens

NewScopedTokens builds an empty issuer.

func (*ScopedTokens) Issue added in v0.36.0

func (s *ScopedTokens) Issue(userID string, tagIDs []string) (string, error)

Issue mints a sub-agent token bound to userID with exactly tagIDs. The principal is demoted to RoleUser (see IssueFor for the top-level case).

The caller is responsible for having already intersected tagIDs down to what the user may reach — this type stores what it is given and never widens it, but it also cannot verify the intersection for you.

func (*ScopedTokens) IssueFor added in v1.0.0

func (s *ScopedTokens) IssueFor(userID string, tagIDs []string, stripAdmin bool) (string, error)

IssueFor mints a token and says explicitly whether the principal should be demoted to RoleUser on every request. See scopedGrant.stripAdmin.

func (*ScopedTokens) IssueForSession added in v1.2.9

func (s *ScopedTokens) IssueForSession(userID, sessionID string, tagIDs []string, stripAdmin bool) (string, error)

IssueForSession mints a token that also remembers WHICH session it was minted for, so calls arriving with it resolve to that conversation without the model passing a session_id. sessionID may be empty when the minter does not know it yet (sub-agents); the grant is then exactly what IssueFor produced before.

func (*ScopedTokens) LoadHandoff added in v1.2.9

func (s *ScopedTokens) LoadHandoff(dir string) int

LoadHandoff imports grants left by a predecessor and deletes the file. It is safe to call when there is nothing to import: no file means no predecessor, which is the normal case for a cold start.

Returns how many grants were adopted.

func (*ScopedTokens) Lookup added in v0.36.0

func (s *ScopedTokens) Lookup(token string) (userID string, tagIDs []string, ok bool)

Lookup resolves a token to its principal. ok is false for unknown or expired tokens.

func (*ScopedTokens) LookupGrant added in v1.0.0

func (s *ScopedTokens) LookupGrant(token string) (userID string, tagIDs []string, stripAdmin bool, ok bool)

LookupGrant resolves a token and also reports whether the principal must be demoted to RoleUser.

func (*ScopedTokens) LookupSession added in v1.2.9

func (s *ScopedTokens) LookupSession(token string) (sessionID string, ok bool)

LookupSession resolves the session a token was minted for. ok is false for unknown or expired tokens; a valid token minted without a session returns ok=true with an empty id, which callers read as "no opinion" and fall back to whatever the request itself carries.

func (*ScopedTokens) Revoke added in v0.36.0

func (s *ScopedTokens) Revoke(token string)

Revoke drops a token. Called when a delegation reaches a terminal state so a finished child cannot keep calling tools.

An opaque grant is deleted. A signed one cannot be — the statement is already out there — so its id is remembered until the moment it would have expired anyway, and every lookup checks that list first.

func (*ScopedTokens) SaveHandoff added in v1.2.9

func (s *ScopedTokens) SaveHandoff(dir string) (int, error)

SaveHandoff writes the still-valid grants so a successor can honour them. An empty set removes any previous file rather than leaving a stale one behind for the next boot to import.

func (*ScopedTokens) Sweep added in v0.36.0

func (s *ScopedTokens) Sweep()

Sweep drops expired grants, and the revocations that outlived the tokens they were holding down. Cheap; safe to call periodically.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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