mirror of
https://github.com/PerpetualSoftware/pad.git
synced 2026-10-03 12:10:31 +00:00
d84f1180a7
* feat(mcp): pluggable Dispatcher + HTTPHandlerDispatcher for remote MCP (TASK-965)
Architectural prerequisite for PLAN-943's remote MCP at /mcp. The
existing ExecDispatcher (PLAN-942) shells out to the pad binary and
inherits credentials from ~/.pad/credentials.json — fine for local
stdio MCP where the user IS the subprocess owner, but unworkable for
a multi-tenant /mcp endpoint where the dispatcher must serve many
OAuth-authenticated users from a single process.
This PR ships the alternative path: HTTPHandlerDispatcher calls
pad-cloud's existing HTTP handler chain in-process, with the
requesting user attached via context. Same handlers, same audit /
event-bus / webhook plumbing — just no fork().
## What's in
- internal/mcp/dispatch.go: keeps the existing Dispatcher interface
(so ExecDispatcher unchanged) and adds a context-keyed
WithDispatchInput helper. The registry attaches the original JSON
input map to the dispatch context so dispatchers that prefer
structured data over reverse-parsed cliArgs can use it.
- internal/mcp/registry.go: forwards the merged input (user-supplied
values + session workspace + root flags) to the dispatcher via
WithDispatchInput. ExecDispatcher ignores it.
- internal/mcp/dispatch_http.go (new): HTTPHandlerDispatcher
implementation with a routeTable[cmdPath]→RouteMapper mapping. Seed
entry: `item create`. Adding more commands is one RouteMapper per
cmdPath plus a routeTable insert.
- internal/server/context.go (new): exported WithCurrentUser /
WithAPITokenAuth / WithTokenWorkspaceID + read-only
CurrentUserFromContext / IsAPITokenFromContext. Lets internal/mcp
synthesize an authenticated request without reaching the
package-private context keys.
- internal/server/middleware_csrf.go: extends the existing "Bearer
token requests skip CSRF" rule to also honor the ctxIsAPIToken
context flag. Same semantic — non-cookie auth means no CSRF risk —
but covers the in-process dispatch path where TokenAuth never sets
the Authorization header. Safe because ctxIsAPIToken can only be
set by trusted in-process code (TokenAuth on the live Bearer path,
or server.WithAPITokenAuth from the dispatcher).
## What's tested
- Unit:
- TestHTTPHandlerDispatcher_RoutesItemCreate — full happy path
with a recordingHandler asserting method/path/body/user-context.
- TestHTTPHandlerDispatcher_UnsupportedToolReturnsErrorResult —
tools not yet in the routeTable produce IsError-flagged results
rather than panicking.
- TestHTTPHandlerDispatcher_NoUserReturnsErrorResult — UserResolver
returning nil produces an IsError, never a nil-deref.
- TestHTTPHandlerDispatcher_HandlerErrorSurfacesAsToolError — 4xx
handler responses come back as IsError MCP results matching
ExecDispatcher's `pad <cmd> failed: <stderr>` format.
- mapItemCreate validation + parseFieldKVP variants.
- Integration: TestHTTPHandlerDispatcher_Integration drives the full
*server.Server (real chi router, real SQLite store, full middleware
chain) with a synthesized OAuth user and asserts the item lands in
the DB.
## Scope discipline
The DoD called for "dispatch item.create end-to-end" — that's the seed
entry. Wiring the remaining ~70 MCP-exposed commands into routeTable
is naturally a follow-up before TASK-950 ships /mcp to real users
(captured as a separate task post-merge).
Audit-log assertion in the integration test is deferred until TASK-960
(B6b) lands the audit log itself.
Parent: PLAN-943.
* fix(mcp): roll status/priority/category/parent into fields JSON per Codex review (round 1)
Codex caught: mapItemCreate placed status / priority / category /
parent at the top level of the JSON body, but handleCreateItem only
reads them after unmarshalling the Fields string from the request. As
written, MCP-driven `item create` would silently drop those flags —
breaking parity with the CLI for almost every realistic call (parent-
linked tasks, priority-set items, status-overridden ideas, etc.).
Mirrored the CLI's behaviour (cmd/pad/main.go ~L2200): build a fields
map from the named flags, overlay the repeatable --field entries on
top, JSON-encode into ItemCreate.Fields. The handler's existing
schema-validation + parent-resolution path now runs unchanged.
Repeatable --field still wins last-write — locked into a new test so
it doesn't drift.
Also rejects --assign / --role with a clear error rather than silently
dropping them. The CLI resolves user-name → user-ID and role-slug →
role-ID via additional API calls before posting; replicating that
pre-resolution belongs in a follow-up that expands the route table for
production use. Failing loudly is better than partial parity.
Tests:
- TestHTTPHandlerDispatcher_RoutesItemCreate now asserts the
status/priority/category/parent values land in fields, not the top
level — guards against the regression directly.
- TestMapItemCreate_ExplicitFieldOverridesNamedFlag locks the
last-write-wins precedence between --status and --field status=...
- TestMapItemCreate_RejectsUnsupportedAssignRole asserts the
defensive error path for the deferred flags.
Parent: PLAN-943.
* fix(mcp): persist source=cli for HTTPHandlerDispatcher calls per Codex review (round 2)
Codex caught: actorFromRequest derives source from the Authorization
header — without one, dispatcher-driven calls would persist
source="web" instead of source="cli", regressing dashboard/standup/
audit attribution vs. ExecDispatcher.
Same pattern as the round-1 CSRF fix: extend actorFromRequest to also
honor the ctxIsAPIToken context flag (which TokenAuth sets on the live
Bearer-auth path and HTTPHandlerDispatcher sets via
server.WithAPITokenAuth on synthesized requests). Both signals mean
"non-cookie authenticated, attribute as CLI/agent traffic".
Integration test now asserts source="cli" on the created item, so any
future regression of this attribution surfaces immediately.
Parent: PLAN-943.
* fix(mcp): normalize collection aliases in HTTPHandlerDispatcher per Codex review (round 3)
Codex caught: CLI's `item create task ...` works because
cmd/pad/main.go's normalizeCollectionSlug maps singular/short forms
("task" → "tasks", "doc" → "docs", etc.) to the canonical slug
before posting. HTTPHandlerDispatcher's mapItemCreate skipped that
step, so the same documented call shape would 404 through the HTTP
transport even though it worked through ExecDispatcher.
Extracted the alias map to internal/collections.NormalizeSlug so the
two transports stay in lockstep without duplication. cmd/pad/main.go's
normalizeCollectionSlug now delegates to it; the in-process
dispatcher calls it from mapItemCreate after pulling the collection
out of input.
TestMapItemCreate_NormalizesCollectionAliases locks every documented
alias plus a passthrough case for custom collections.
Parent: PLAN-943.
* fix(server): WithTokenWorkspaceID actually clears on empty input per Codex review (round 4)
Codex caught: the docstring said "Pass an empty string to clear" but
the implementation early-returned `ctx` unchanged in that case,
leaving any stale ctxTokenWorkspaceID set further up the chain
active. Always overwrite so the contract holds: passing "" produces
a context where tokenWorkspaceID(r) returns "", same as a never-set
context.
Parent: PLAN-943.
75 lines
3.3 KiB
Go
75 lines
3.3 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/PerpetualSoftware/pad/internal/models"
|
|
)
|
|
|
|
// Exported context-key helpers for callers that need to synthesize an
|
|
// authenticated request without going through the auth middleware
|
|
// chain (e.g. the in-process MCP HTTP-handler dispatcher in
|
|
// internal/mcp/dispatch_http.go, which resolves OAuth users via the
|
|
// MCP middleware and then calls the API handler tree directly).
|
|
//
|
|
// The corresponding context keys (ctxCurrentUser, ctxIsAPIToken) are
|
|
// kept package-private so the rest of the codebase can't bypass the
|
|
// middleware accidentally — these functions are the controlled surface.
|
|
|
|
// WithCurrentUser returns ctx decorated with the resolved user, the
|
|
// same way TokenAuth / SessionAuth do during a normal authenticated
|
|
// request. Subsequent handler-tree code can reach the user via the
|
|
// existing currentUser(r) helper without any change.
|
|
//
|
|
// Pass nil to clear (rare; mostly useful in tests).
|
|
func WithCurrentUser(ctx context.Context, user *models.User) context.Context {
|
|
return context.WithValue(ctx, ctxCurrentUser, user)
|
|
}
|
|
|
|
// WithAPITokenAuth marks ctx as authenticated via an API token, the
|
|
// same way TokenAuth does on the Bearer-token path. Required when
|
|
// dispatching through the in-process handler from the OAuth-protected
|
|
// /mcp endpoint, because the auth middleware's downstream checks
|
|
// (e.g. CSRF exemption for token-auth callers) read ctxIsAPIToken to
|
|
// distinguish from session-cookie traffic.
|
|
func WithAPITokenAuth(ctx context.Context) context.Context {
|
|
return context.WithValue(ctx, ctxIsAPIToken, true)
|
|
}
|
|
|
|
// WithTokenWorkspaceID returns ctx decorated with a workspace-scope
|
|
// hint, mirroring TokenAuth's behaviour for workspace-scoped API
|
|
// tokens. Pass an empty string to clear (overrides any previous
|
|
// scope-binding to ""; downstream readers via tokenWorkspaceID(r)
|
|
// see the same "no scope" they would for a never-set context).
|
|
//
|
|
// The MCP dispatcher uses this to forward the OAuth-token's allowed
|
|
// workspace to the handler tree where existing access-control logic
|
|
// reads it via tokenWorkspaceID(r).
|
|
func WithTokenWorkspaceID(ctx context.Context, workspaceID string) context.Context {
|
|
// Always overwrite — passing "" must clear a stale scope set
|
|
// further up the context chain. Returning ctx unchanged on the
|
|
// empty path was a bug Codex caught in PR #343 review round 4.
|
|
return context.WithValue(ctx, ctxTokenWorkspaceID, workspaceID)
|
|
}
|
|
|
|
// CurrentUserFromContext returns the user attached by WithCurrentUser
|
|
// (or by the standard auth middleware), and a boolean signalling
|
|
// whether one was present. Read-only accessor — callers that need to
|
|
// set the user must use WithCurrentUser.
|
|
//
|
|
// Exported so out-of-package callers (notably internal/mcp's HTTP
|
|
// dispatcher tests) can verify the user round-trips correctly through
|
|
// the synthesized request without reaching into private helpers.
|
|
func CurrentUserFromContext(ctx context.Context) (*models.User, bool) {
|
|
v, ok := ctx.Value(ctxCurrentUser).(*models.User)
|
|
return v, ok && v != nil
|
|
}
|
|
|
|
// IsAPITokenFromContext reports whether the request was authenticated
|
|
// via an API token (vs. a session cookie or CLI session token).
|
|
// Mirrors the package-private isAPIToken(r) helper.
|
|
func IsAPITokenFromContext(ctx context.Context) bool {
|
|
v, _ := ctx.Value(ctxIsAPIToken).(bool)
|
|
return v
|
|
}
|