Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(apps): connect remote MCP apps over OAuth, starting with Mobbin (MUL-9792) (#11162)
Jiayuan Zhangd5792738f9ba
diff --git a/.env.example b/.env.exampleindex e7655370f4..77362ea693 100644--- a/.env.example+++ b/.env.example@@ -718,6 +718,14 @@ MULTICA_LARK_WS_PROXY_URL=# Generate one with: openssl rand -base64 32MULTICA_DINGTALK_SECRET_KEY=+# Remote MCP apps in Connected Apps (Settings → Connected apps, e.g. Mobbin)+# Off until MULTICA_APPS_SECRET_KEY is set — a base64-encoded 32-byte key+# that encrypts each account's OAuth tokens at rest. They also need Connected+# Apps itself, which runs on Composio and is not part of the self-host stack+# yet. Keep it stable: rotating it signs every remote account out.+# Generate one with: openssl rand -base64 32+MULTICA_APPS_SECRET_KEY=+# Slack bot integration (Settings → Integrations → Slack)# Off until MULTICA_SLACK_SECRET_KEY is set — a base64-encoded 32-byte key# that encrypts each installation's bot and app tokens at rest. Leave emptydiff --git a/packages/views/settings/components/apps-settings.test.tsx b/packages/views/settings/components/apps-settings.test.tsxindex e578a0bc5d..2c9d4dfe9f 100644--- a/packages/views/settings/components/apps-settings.test.tsx+++ b/packages/views/settings/components/apps-settings.test.tsx@@ -10,6 +10,7 @@ import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";import enBilling from "../../locales/en/billing.json";import { toast } from "sonner";+import { openExternal } from "../../platform";import { AppsSettings } from "./apps-settings";const nav = vi.hoisted(() => ({@@ -22,9 +23,13 @@ vi.mock("@multica/core/api", async (importOriginal) => ({...(await importOriginal<typeof import("@multica/core/api")>()),api: {getAppsOverview: vi.fn(), listAppCatalog: vi.fn(), updateAppSettings: vi.fn(), updateAppRules: vi.fn(),- getWorkspaceFeatures: vi.fn(),+ getWorkspaceFeatures: vi.fn(), connectApp: vi.fn(),},}));+vi.mock("../../platform", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../platform")>()),+ openExternal: vi.fn(),+}));vi.mock("@multica/core/paths", async (importOriginal) => ({...(await importOriginal<object>()),useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),@@ -106,6 +111,22 @@ it("lets a member recover only their personal account and keeps failed confirmatexpect(screen.getAllByText("Previous action restrictions are still limiting this account.")).toHaveLength(1);});+it("reconnects an expired account from its row", async () => {+ overview.personal = [+ ...overview.personal,+ { id: "personal-2", toolkit_slug: "mobbin", status: "expired", connected_at: "", last_used_at: null },+ ];+ vi.mocked(api.connectApp).mockResolvedValue({ redirect_url: "https://auth.example.com/authorize?state=s" });+ const user = userEvent.setup();+ renderSettings();+ expect(await screen.findByText("Needs reconnecting")).toBeVisible();+ const buttons = screen.getAllByRole("button", { name: "Reconnect" });+ expect(buttons).toHaveLength(1);+ await user.click(buttons[0]!);+ await waitFor(() => expect(api.connectApp).toHaveBeenCalledWith("personal", "mobbin"));+ expect(openExternal).toHaveBeenCalledWith("https://auth.example.com/authorize?state=s", { webTarget: "same-tab" });+});+it("opens a connection dialog for the section that launched it", async () => {const user = userEvent.setup();renderSettings();diff --git a/packages/views/settings/components/apps-settings.tsx b/packages/views/settings/components/apps-settings.tsxindex c9a1f2ab50..8631ebd53d 100644--- a/packages/views/settings/components/apps-settings.tsx+++ b/packages/views/settings/components/apps-settings.tsx@@ -41,7 +41,7 @@ import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";import { SavedAppRestriction } from "../../common/saved-app-restriction";import { useT, useTimeAgo } from "../../i18n";import { useNavigation } from "../../navigation";-import { isDesktopShell } from "../../platform";+import { isDesktopShell, openExternal } from "../../platform";import { AddAppDialog } from "./add-app-dialog";import { AppAccountDialog } from "./app-account-dialog";import { SettingsCard, SettingsSection } from "./settings-layout";@@ -269,8 +269,22 @@ function AccountRow({const timeAgo = useTimeAgo();const { getActorName } = useActorName();const restore = useRestoreAppAccess();+ const [reconnecting, setReconnecting] = useState(false);const name = app?.name || connection.toolkit_slug;const expired = connection.status === "expired";++ async function reconnect() {+ setReconnecting(true);+ try {+ const { redirect_url } = await api.connectApp(scope, connection.toolkit_slug);+ openExternal(redirect_url, { webTarget: "same-tab" });+ // Desktop opens the hosted flow in the system browser and stays here.+ if (isDesktopShell()) setReconnecting(false);+ } catch (e) {+ toast.error(e instanceof Error && e.message ? e.message : t(($) => $.connected_apps.toast_failed));+ setReconnecting(false);+ }+ }const meta = [scope === "team" && connection.connected_by? t(($) => $.connected_apps.connected_by, { name: getActorName("member", connection.connected_by) })@@ -300,6 +314,11 @@ function AccountRow({</div>{canManage && (<>+ {expired && (+ <Button variant="outline" size="sm" onClick={reconnect} disabled={reconnecting}>+ {t(($) => $.connected_apps.reconnect)}+ </Button>+ )}<Button variant="ghost" size="sm" onClick={onOpen}>{t(($) => $.connected_apps.activity)}</Button>diff --git a/scripts/selfhost-config.test.sh b/scripts/selfhost-config.test.shindex 49d37d73af..84f0a91151 100755--- a/scripts/selfhost-config.test.sh+++ b/scripts/selfhost-config.test.sh@@ -157,6 +157,7 @@ POSTHOG_HOST Cloud product analytics (PostHog)FF_BILLING_WORKSPACE_SUBSCRIPTIONS needs multica-cloud billing, which self-host does not runCLOUDFRONT_PRIVATE_KEY_SECRET Cloud reads the key from AWS Secrets Manager; it outranks CLOUDFRONT_PRIVATE_KEY and .env.example ships a default name, so passing it would break the key self-host does passMULTICA_FEATURE_FLAGS_FILE a path inside the container: set it in a compose override together with the mount; FF_ variables cover single flags+MULTICA_APPS_SECRET_KEY remote MCP apps run inside Connected Apps, which needs Composio; self-host does not configure Composio yetLOCAL_UPLOAD_DIR uploads must stay on the backend_uploads volume mounted at /app/data/uploadsMULTICA_SERVER_URL the server only writes this name into agent setup commands; the daemon sets itMULTICA_WORKSPACE_ID the server only writes this name into agent setup commands; the daemon sets itdiff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 43451fe8c4..043d41b4be 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "720_remote_app_oauth_client_idx": "uq_remote_app_oauth_client_app_redirect",+ "721_remote_app_connection_owner_idx": "uq_remote_app_connection_owner","676_chat_wakeup_due_idx": "idx_chat_wakeup_due","677_chat_wakeup_session_idx": "idx_chat_wakeup_session","678_chat_wakeup_requester_idx": "idx_chat_wakeup_requester",diff --git a/server/cmd/server/private_project_routes_test.go b/server/cmd/server/private_project_routes_test.goindex 3ae7ccb20c..90d69c8bca 100644--- a/server/cmd/server/private_project_routes_test.go+++ b/server/cmd/server/private_project_routes_test.go@@ -128,6 +128,7 @@ var routeParamsOutsideProjects = map[string]outsideProjectParam{"plugins/{installationId}": {why: "a plugin installation"},"packages/{packageId}": {why: "a plugin package"},"mcp/{hookKey}": {why: "a plugin MCP hook"},+ "mcp/{app}": {why: "a built-in remote MCP app slug, reached with a task token"},"surfaces/{surfaceKey}": {why: "a plugin surface"},"groups/{conversationId}": {why: "a DingTalk group"},"install/{sessionId}": {why: "an integration install session"},diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 90663802eb..db4d80af36 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1404,17 +1404,31 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Connected Apps v2 (MUL-8516): runs reach their apps// through the Multica gateway, which holds the Composio// key and applies account rules and confirmations.- appsSvc, aerr := connectedapps.New(connectedapps.Config{+ appsCfg := connectedapps.Config{Queries: queries,Composio: svc,TokenSecret: connectedapps.DeriveTokenSecret(stateSecret),PublicBaseURL: callbackBase,Bus: bus,- })+ }+ // Remote MCP apps (MUL-9792) store OAuth tokens, so+ // they need their own at-rest key; without it they+ // stay off and Composio apps work as before.+ if appsKey, kerr := secretbox.LoadKey("MULTICA_APPS_SECRET_KEY"); kerr == nil {+ if box, berr := secretbox.New(appsKey); berr == nil {+ appsCfg.SecretBox, appsCfg.DB = box, pool+ } else {+ slog.Error("connected apps: secretbox.New failed; remote MCP apps disabled", "error", berr)+ }+ } else {+ slog.Info("connected apps: remote MCP apps disabled (MULTICA_APPS_SECRET_KEY not set)")+ }+ appsSvc, aerr := connectedapps.New(appsCfg)if aerr != nil {slog.Error("connected apps: init failed; agents run without apps", "error", aerr)} else {appsSvc.SetResumer(h)+ appsSvc.SetTeamConnectGate(h.TeamAppConnectGate)h.ConnectedApps = appsSvc}// Stage 3 (MUL-3721) hook: feed the per-task MCP@@ -1706,6 +1720,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Apps MCP gateway (MUL-8516). Outside the Auth group: a run presents its// task-scoped bearer token, verified by the gateway itself.r.Post("/api/apps/mcp", h.AppsGateway)+ r.Post("/api/apps/mcp/{app}", h.AppsRemoteGateway)+ // Remote MCP app OAuth callback (MUL-9792). Public for the same reason+ // as the Composio callback; the sealed state identifies the handshake.+ r.Get("/api/apps/oauth/callback", h.AppsOAuthCallback)// Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {diff --git a/server/internal/connectedapps/catalog.go b/server/internal/connectedapps/catalog.goindex e6030d1bf2..10f532280c 100644--- a/server/internal/connectedapps/catalog.go+++ b/server/internal/connectedapps/catalog.go@@ -60,6 +60,7 @@ var curatedApps = []CuratedApp{{Slug: "jira"},{Slug: "asana"},{Slug: "figma"},+ {Slug: "mobbin", Scope: ScopePersonal},{Slug: "sentry", Scope: ScopeTeam},{Slug: "posthog", Scope: ScopeTeam},{Slug: "hubspot", Scope: ScopeTeam},diff --git a/server/internal/connectedapps/gateway.go b/server/internal/connectedapps/gateway.goindex 720be946ef..542199e235 100644--- a/server/internal/connectedapps/gateway.go+++ b/server/internal/connectedapps/gateway.go@@ -65,6 +65,10 @@ type run struct {// authenticates with the bearer token minted at claim; the token only works// while its task is dispatched or running.func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ s.serveRPC(w, r, s.dispatch)+}++func (s *Service) serveRPC(w http.ResponseWriter, r *http.Request, dispatch func(context.Context, *run, rpcRequest) (rpcResponse, bool)) {if r.Method != http.MethodPost {w.Header().Set("Allow", http.MethodPost)http.Error(w, "method not allowed", http.StatusMethodNotAllowed)@@ -103,7 +107,7 @@ func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {}var out []rpcResponsefor _, req := range reqs {- resp, notify := s.dispatch(r.Context(), rn, req)+ resp, notify := dispatch(r.Context(), rn, req)if !notify {out = append(out, resp)}@@ -331,6 +335,9 @@ func (s *Service) toolListApps(ctx context.Context, rn *run) map[string]any {Account string `json:"account"`Level string `json:"level"`Status string `json:"status"`+ // Server is set for an app whose tools are called directly on its+ // own MCP server rather than through apps_run_tool.+ Server string `json:"server,omitempty"`}out := []appView{}for slug, app := range rn.apps {@@ -342,10 +349,14 @@ func (s *Service) toolListApps(ctx context.Context, rn *run) map[string]any {if _, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, slug, app.AccountScope); err != nil {status = "not_connected"}- out = append(out, appView{+ view := appView{App: slug, Name: runtimeapps.DisplayNameForToolkitSlug(slug),Account: app.AccountScope, Level: level, Status: status,- })+ }+ if remote, ok := s.RemoteApp(slug); ok {+ view.Name, view.Server = remote.Name, remote.Slug+ }+ out = append(out, view)}sort.Slice(out, func(i, j int) bool { return out[i].App < out[j].App })return jsonResult(map[string]any{"apps": out})@@ -385,6 +396,9 @@ func (s *Service) toolSearch(ctx context.Context, rn *run, slug, query string) mif !ok {return textResult(fmt.Sprintf("app %q is not available to you in this run; call apps_list", slug), true)}+ if remote, ok := s.RemoteApp(slug); ok {+ return remoteServerHint(remote)+ }tools, err := s.composio.ListToolkitTools(ctx, slug)if err != nil {slog.Warn("connectedapps: list tools failed", "toolkit", slug, "error", err)@@ -442,6 +456,9 @@ func (s *Service) toolGet(ctx context.Context, rn *run, toolSlug string) map[strif !ok {return textResult("this tool does not belong to an app you can use in this run", true)}+ if remote, ok := s.RemoteApp(app.ToolkitSlug); ok {+ return remoteServerHint(remote)+ }tool, err := s.composio.GetTool(ctx, app.ToolkitSlug, toolSlug)if err != nil {return textResult("tool not found", true)@@ -466,6 +483,9 @@ func (s *Service) toolRun(ctx context.Context, rn *run, toolSlug string, args mareturn textResult("this tool does not belong to an app you can use in this run", true)}slug := NormalizeSlug(app.ToolkitSlug)+ if remote, ok := s.RemoteApp(slug); ok {+ return remoteServerHint(remote)+ }tool, err := s.composio.GetTool(ctx, slug, toolSlug)if err != nil {return textResult("tool not found", true)@@ -484,30 +504,8 @@ func (s *Service) toolRun(ctx context.Context, rn *run, toolSlug string, args ma}return textResult("could not resolve the account for this app", true)}- switch policy {- case PolicyBlock:- call.outcome = "blocked"- first := s.firstBlock(ctx, call)- s.recordCall(ctx, call)- if first && rn.triggeredBy.Valid {- s.notify(ctx, db.AppActionRequest{- WorkspaceID: rn.workspaceID, Status: "blocked", Kind: KindAction,- TaskID: rn.task.ID, AgentID: rn.agent.ID, IssueID: rn.task.IssueID, ChatSessionID: rn.task.ChatSessionID,- ApproverUserID: rn.triggeredBy, AccountScope: app.AccountScope,- ToolkitSlug: slug, ToolSlug: tool.Slug, ActionClass: class,- }, NotifActionResult)- }- return textResult(fmt.Sprintf("blocked: %s calls (%s) are not allowed for you on %s. Do not work around this; tell the person what you would have done.", class, tool.Slug, slug), true)- }- // Tool lookup may involve a network call, and one gateway request may- // contain a batch. Check again immediately before allowing execution.- if !s.mayRun(ctx, rn.task, rn.agent) {- return textResult("this run is no longer allowed to use this agent", true)- }- if s.overLimit(ctx, rn.workspaceID, slug, acct) {- call.outcome = "rate_limited"- s.recordCall(ctx, call)- return textResult(fmt.Sprintf("rate limited: this %s account already ran %d calls in the last minute. Wait a minute before the next call, and batch work where the app allows it.", slug, s.perMinute), true)+ if refusal := s.refuseCall(ctx, rn, app, &call, policy); refusal != nil {+ return refusal}resp, err := s.composio.ExecuteTool(ctx, acct.connectedAccountID, acct.composioUserID, *tool, args)s.touch(ctx, rn.workspaceID, acct)@@ -528,6 +526,37 @@ func (s *Service) toolRun(ctx context.Context, rn *run, toolSlug string, args mareturn jsonResult(resp.Data)}+// refuseCall applies what stands between an allowed policy and executing a+// call: a blocking rule, the run losing access, and the account's rate limit.+// It records and returns the refusal, or nil when the call may run.+func (s *Service) refuseCall(ctx context.Context, rn *run, app db.AgentApp, call *toolCall, policy string) map[string]any {+ if policy == PolicyBlock {+ call.outcome = "blocked"+ first := s.firstBlock(ctx, *call)+ s.recordCall(ctx, *call)+ if first && rn.triggeredBy.Valid {+ s.notify(ctx, db.AppActionRequest{+ WorkspaceID: rn.workspaceID, Status: "blocked", Kind: KindAction,+ TaskID: rn.task.ID, AgentID: rn.agent.ID, IssueID: rn.task.IssueID, ChatSessionID: rn.task.ChatSessionID,+ ApproverUserID: rn.triggeredBy, AccountScope: app.AccountScope,+ ToolkitSlug: call.toolkit, ToolSlug: call.tool, ActionClass: call.class,+ }, NotifActionResult)+ }+ return textResult(fmt.Sprintf("blocked: %s calls (%s) are not allowed for you on %s. Do not work around this; tell the person what you would have done.", call.class, call.tool, call.toolkit), true)+ }+ // Tool lookup may involve a network call, and one gateway request may+ // contain a batch. Check again immediately before allowing execution.+ if !s.mayRun(ctx, rn.task, rn.agent) {+ return textResult("this run is no longer allowed to use this agent", true)+ }+ if s.overLimit(ctx, rn.workspaceID, call.toolkit, call.acct) {+ call.outcome = "rate_limited"+ s.recordCall(ctx, *call)+ return textResult(fmt.Sprintf("rate limited: this %s account already ran %d calls in the last minute. Wait a minute before the next call, and batch work where the app allows it.", call.toolkit, s.perMinute), true)+ }+ return nil+}+func (s *Service) toolRequestConnection(ctx context.Context, rn *run, slug, summary string) map[string]any {slug = NormalizeSlug(slug)app, ok := rn.apps[slug]diff --git a/server/internal/connectedapps/remote.go b/server/internal/connectedapps/remote.gonew file mode 100644index 0000000000..4f3ef4075e--- /dev/null+++ b/server/internal/connectedapps/remote.go@@ -0,0 +1,697 @@+package connectedapps++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ composiointeg "github.com/multica-ai/multica/server/internal/integrations/composio"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/remotemcp"+)++// RemoteApp is an app whose own MCP server Multica connects to as an OAuth+// client, instead of through Composio. Adding one is configuration only: the+// server must publish OAuth discovery metadata (RFC 9728 / RFC 8414) and+// accept dynamic client registration.+type RemoteApp struct {+ Slug string+ Name string+ Endpoint string+ Category string+}++// BuiltinRemoteApps are the remote MCP apps every deployment offers when+// remote apps are configured.+var BuiltinRemoteApps = []RemoteApp{+ {Slug: "mobbin", Name: "Mobbin", Endpoint: "https://api.mobbin.com/mcp", Category: "design"},+}++// RemoteProvider tags a remote MCP app in a run's connected-app metadata. Its+// tools are served under their own MCP server, not the apps_* meta tools.+const RemoteProvider = "multica_remote"++// RemoteCallbackPath is the public OAuth redirect URI path.+const RemoteCallbackPath = "/api/apps/oauth/callback"++const (+ remoteStateTTL = 10 * time.Minute+ remoteRefreshSkew = 2 * time.Minute+ remoteToolCacheTTL = 10 * time.Minute+ // Covers the token request (its HTTP client gives up at 30s) and the save.+ remoteRefreshTimeout = 40 * time.Second+)++// ErrRemoteState means the callback's state is missing, tampered with, or+// expired. The handler shows a generic failure for it.+var ErrRemoteState = errors.New("connectedapps: invalid connect state")++// TxStarter begins the transaction a token refresh runs in.+type TxStarter interface {+ Begin(ctx context.Context) (pgx.Tx, error)+}++// Sealer encrypts tokens at rest; *secretbox.Box implements it.+type Sealer interface {+ Seal(plaintext []byte) ([]byte, error)+ Open(sealed []byte) ([]byte, error)+}++// RemoteUpstream is the network side of remote apps. remotemcpUpstream is the+// production implementation; tests substitute a fake.+type RemoteUpstream interface {+ DiscoverOAuth(ctx context.Context, endpoint string) (remotemcp.OAuthMetadata, error)+ Register(ctx context.Context, metadata remotemcp.OAuthMetadata, redirectURI string) (remotemcp.OAuthClientRegistration, error)+ Exchange(ctx context.Context, tokenEndpoint, resource, code, redirectURI, verifier string, client remotemcp.OAuthClientRegistration) (remotemcp.OAuthTokenResponse, error)+ Refresh(ctx context.Context, tokenEndpoint, resource, refreshToken string, client remotemcp.OAuthClientRegistration) (remotemcp.OAuthTokenResponse, error)+ ListTools(ctx context.Context, endpoint, accessToken string) ([]json.RawMessage, error)+ CallTool(ctx context.Context, endpoint, accessToken, name string, args map[string]any) (json.RawMessage, error)+}++type remotemcpUpstream struct{}++func (remotemcpUpstream) DiscoverOAuth(ctx context.Context, endpoint string) (remotemcp.OAuthMetadata, error) {+ return remotemcp.DiscoverOAuth(ctx, endpoint, nil)+}++func (remotemcpUpstream) Register(ctx context.Context, metadata remotemcp.OAuthMetadata, redirectURI string) (remotemcp.OAuthClientRegistration, error) {+ return remotemcp.RegisterOAuthClient(ctx, metadata, redirectURI)+}++func (remotemcpUpstream) Exchange(ctx context.Context, tokenEndpoint, resource, code, redirectURI, verifier string, client remotemcp.OAuthClientRegistration) (remotemcp.OAuthTokenResponse, error) {+ return remotemcp.ExchangeOAuthCode(ctx, tokenEndpoint, resource, code, redirectURI, verifier, client)+}++func (remotemcpUpstream) Refresh(ctx context.Context, tokenEndpoint, resource, refreshToken string, client remotemcp.OAuthClientRegistration) (remotemcp.OAuthTokenResponse, error) {+ return remotemcp.RefreshOAuthToken(ctx, tokenEndpoint, resource, refreshToken, client)+}++func bearer(token string) http.Header {+ return http.Header{"Authorization": {"Bearer " + token}}+}++func (remotemcpUpstream) ListTools(ctx context.Context, endpoint, accessToken string) ([]json.RawMessage, error) {+ session, err := remotemcp.OpenSession(ctx, endpoint, bearer(accessToken))+ if err != nil {+ return nil, err+ }+ return session.ListTools(ctx)+}++func (remotemcpUpstream) CallTool(ctx context.Context, endpoint, accessToken, name string, args map[string]any) (json.RawMessage, error) {+ session, err := remotemcp.OpenSession(ctx, endpoint, bearer(accessToken))+ if err != nil {+ return nil, err+ }+ return session.CallTool(ctx, name, args)+}++// remoteSupport is the Service state remote apps need. It is nil when the+// deployment has no MCP apps secret key.+type remoteSupport struct {+ apps map[string]RemoteApp+ order []string+ box Sealer+ db TxStarter+ upstream RemoteUpstream+ redirectURI string+ teamGate composiointeg.TeamConnectGate++ mu sync.Mutex+ tools map[string]remoteToolCache+}++type remoteToolCache struct {+ at time.Time+ tools []RemoteTool+}++// RemoteTool is one tool an app's MCP server lists.+type RemoteTool struct {+ Name string+ Description string+ // Tags carries the server's readOnlyHint / destructiveHint annotations+ // for Classify.+ Tags []string+ Raw json.RawMessage+}++func newRemoteSupport(cfg Config, publicBase string) *remoteSupport {+ if cfg.SecretBox == nil || cfg.DB == nil {+ return nil+ }+ apps := cfg.RemoteApps+ if apps == nil {+ apps = BuiltinRemoteApps+ }+ upstream := cfg.RemoteUpstream+ if upstream == nil {+ upstream = remotemcpUpstream{}+ }+ r := &remoteSupport{+ apps: map[string]RemoteApp{},+ box: cfg.SecretBox,+ db: cfg.DB,+ upstream: upstream,+ redirectURI: publicBase + RemoteCallbackPath,+ tools: map[string]remoteToolCache{},+ }+ for _, app := range apps {+ slug := NormalizeSlug(app.Slug)+ app.Slug = slug+ r.apps[slug] = app+ r.order = append(r.order, slug)+ }+ return r+}++// RemoteApp returns the remote app for slug when remote apps are enabled.+func (s *Service) RemoteApp(slug string) (RemoteApp, bool) {+ if s.remote == nil {+ return RemoteApp{}, false+ }+ app, ok := s.remote.apps[NormalizeSlug(slug)]+ return app, ok+}++// RemoteApps lists the enabled remote apps in catalog order.+func (s *Service) RemoteApps() []RemoteApp {+ if s.remote == nil {+ return nil+ }+ out := make([]RemoteApp, 0, len(s.remote.order))+ for _, slug := range s.remote.order {+ out = append(out, s.remote.apps[slug])+ }+ return out+}++// SetTeamConnectGate installs the plan check a new team account must pass,+// the same one Composio team accounts use. Call it before serving requests.+func (s *Service) SetTeamConnectGate(gate composiointeg.TeamConnectGate) {+ if s.remote != nil {+ s.remote.teamGate = gate+ }+}++// remoteState is the connect handshake carried through the browser. It is+// sealed, not just signed: it holds the PKCE verifier.+type remoteState struct {+ App string `json:"a"`+ Scope string `json:"s"`+ Owner string `json:"o"`+ Actor string `json:"u"`+ Client string `json:"c"`+ Verifier string `json:"v"`+ ReturnTo string `json:"r,omitempty"`+ Exp int64 `json:"e"`+}++// RemoteConnectResult is what a completed (or failed) handshake was for.+type RemoteConnectResult struct {+ Slug string+ Scope string+ Owner pgtype.UUID+ Actor pgtype.UUID+ ReturnTo string+}++// BeginRemoteConnect returns the authorization URL that connects an account+// for a remote app. owner is the workspace for a team account and the actor+// for a personal one; the caller has already checked the actor may do this.+func (s *Service) BeginRemoteConnect(ctx context.Context, slug, scope string, owner, actor pgtype.UUID, returnTo string) (string, error) {+ app, ok := s.RemoteApp(slug)+ if !ok {+ return "", composiointeg.ErrToolkitNotSupported+ }+ if !ValidScope(scope) || !owner.Valid || !actor.Valid {+ return "", errors.New("connectedapps: invalid remote connect owner")+ }+ if !composiointeg.SafeReturnPath(returnTo) {+ returnTo = ""+ }+ client, err := s.remoteOAuthClient(ctx, app)+ if err != nil {+ return "", err+ }+ verifier, err := randomToken()+ if err != nil {+ return "", err+ }+ state, err := s.sealState(remoteState{+ App: app.Slug, Scope: scope, Owner: util.UUIDToString(owner), Actor: util.UUIDToString(actor),+ Client: util.UUIDToString(client.ID), Verifier: verifier, ReturnTo: returnTo,+ Exp: s.now().Add(remoteStateTTL).Unix(),+ })+ if err != nil {+ return "", err+ }+ return remotemcp.BuildAuthorizationURL(+ remotemcp.OAuthMetadata{ResourceEndpoint: app.Endpoint, AuthorizationEndpoint: client.AuthorizationEndpoint},+ remotemcp.OAuthClientRegistration{ClientID: client.ClientID},+ s.remote.redirectURI, state, verifier, client.Scope,+ )+}++// CompleteRemoteConnect finishes the handshake the authorization server+// redirected back with, storing the account's tokens. The result names the+// app and owner whenever the state was valid, so a failure can still be shown+// on the right page.+func (s *Service) CompleteRemoteConnect(ctx context.Context, rawState, code, oauthError string) (RemoteConnectResult, error) {+ if s.remote == nil {+ return RemoteConnectResult{}, ErrRemoteState+ }+ st, err := s.openState(rawState)+ if err != nil {+ return RemoteConnectResult{}, err+ }+ owner, err1 := util.ParseUUID(st.Owner)+ actor, err2 := util.ParseUUID(st.Actor)+ clientID, err3 := util.ParseUUID(st.Client)+ app, ok := s.RemoteApp(st.App)+ if err1 != nil || err2 != nil || err3 != nil || !ok || !ValidScope(st.Scope) {+ return RemoteConnectResult{}, ErrRemoteState+ }+ result := RemoteConnectResult{Slug: app.Slug, Scope: st.Scope, Owner: owner, Actor: actor, ReturnTo: st.ReturnTo}+ if oauthError != "" || code == "" {+ return result, fmt.Errorf("connectedapps: authorization not granted")+ }+ client, err := s.q.GetRemoteAppOAuthClientByID(ctx, clientID)+ if err != nil {+ return result, fmt.Errorf("connectedapps: load oauth client: %w", err)+ }+ registration, err := s.registration(client)+ if err != nil {+ return result, err+ }+ tokens, err := s.remote.upstream.Exchange(ctx, client.TokenEndpoint, app.Endpoint, code, s.remote.redirectURI, st.Verifier, registration)+ if err != nil {+ var oauthErr *remotemcp.OAuthError+ if errors.As(err, &oauthErr) && oauthErr.Code == "invalid_client" {+ // The server forgot this client; register again on the next try.+ _ = s.q.DeleteRemoteAppOAuthClient(ctx, client.ID)+ }+ return result, fmt.Errorf("connectedapps: exchange code: %w", err)+ }+ admitted := func(context.Context) {}+ if st.Scope == ScopeTeam && s.remote.teamGate != nil {+ gateAdmitted, err := s.remote.teamGate(ctx, owner, app.Slug)+ if err != nil {+ return result, err+ }+ admitted = gateAdmitted+ }+ access, err := s.seal(tokens.AccessToken)+ if err != nil {+ return result, err+ }+ refresh, err := s.seal(tokens.RefreshToken)+ if err != nil {+ return result, err+ }+ row, err := s.q.UpsertRemoteAppConnection(ctx, db.UpsertRemoteAppConnectionParams{+ AppSlug: app.Slug, Scope: st.Scope, OwnerID: owner, ConnectedBy: actor, OauthClientID: client.ID,+ AccessToken: access, RefreshToken: refresh, ExpiresAt: expiry(s.now(), tokens.ExpiresIn),+ })+ if err != nil {+ return result, fmt.Errorf("connectedapps: save remote account: %w", err)+ }+ s.dropRemoteTools(row.ID)+ admitted(ctx)+ return result, nil+}++// DisconnectRemote forgets a remote account's tokens and marks it revoked.+// It is owner-scoped and idempotent; an unknown id is ErrConnectionNotFound.+func (s *Service) DisconnectRemote(ctx context.Context, id pgtype.UUID, scope string, owner pgtype.UUID) (db.RemoteAppConnection, error) {+ if s.remote == nil {+ return db.RemoteAppConnection{}, composiointeg.ErrConnectionNotFound+ }+ row, err := s.q.GetRemoteAppConnectionForOwner(ctx, db.GetRemoteAppConnectionForOwnerParams{ID: id, Scope: scope, OwnerID: owner})+ if err != nil {+ return db.RemoteAppConnection{}, composiointeg.ErrConnectionNotFound+ }+ if row.Status == "revoked" {+ return row, nil+ }+ if err := s.q.SetRemoteAppConnectionStatus(ctx, db.SetRemoteAppConnectionStatusParams{ID: row.ID, Status: "revoked"}); err != nil {+ return row, fmt.Errorf("connectedapps: revoke remote account: %w", err)+ }+ s.dropRemoteTools(row.ID)+ row.Status = "revoked"+ return row, nil+}++// remoteOAuthClient returns this deployment's client for app, registering one+// the first time.+func (s *Service) remoteOAuthClient(ctx context.Context, app RemoteApp) (db.RemoteAppOauthClient, error) {+ key := db.GetRemoteAppOAuthClientParams{AppSlug: app.Slug, RedirectUri: s.remote.redirectURI}+ row, err := s.q.GetRemoteAppOAuthClient(ctx, key)+ if err == nil {+ return row, nil+ }+ if !isNoRows(err) {+ return row, err+ }+ metadata, err := s.remote.upstream.DiscoverOAuth(ctx, app.Endpoint)+ if err != nil {+ return row, fmt.Errorf("connectedapps: discover oauth: %w", err)+ }+ registration, err := s.remote.upstream.Register(ctx, metadata, s.remote.redirectURI)+ if err != nil {+ return row, fmt.Errorf("connectedapps: register oauth client: %w", err)+ }+ secret, err := s.seal(registration.ClientSecret)+ if err != nil {+ return row, err+ }+ row, err = s.q.InsertRemoteAppOAuthClient(ctx, db.InsertRemoteAppOAuthClientParams{+ AppSlug: app.Slug, RedirectUri: s.remote.redirectURI,+ AuthorizationEndpoint: metadata.AuthorizationEndpoint, TokenEndpoint: metadata.TokenEndpoint,+ Scope: strings.Join(metadata.Scopes, " "), ClientID: registration.ClientID, ClientSecret: secret,+ TokenEndpointAuthMethod: registration.TokenEndpointAuthMethod,+ })+ if isNoRows(err) {+ return s.q.GetRemoteAppOAuthClient(ctx, key)+ }+ return row, err+}++func (s *Service) registration(client db.RemoteAppOauthClient) (remotemcp.OAuthClientRegistration, error) {+ secret, err := s.open(client.ClientSecret)+ if err != nil {+ return remotemcp.OAuthClientRegistration{}, fmt.Errorf("connectedapps: open client secret: %w", err)+ }+ return remotemcp.OAuthClientRegistration{+ ClientID: client.ClientID, ClientSecret: secret, TokenEndpointAuthMethod: client.TokenEndpointAuthMethod,+ }, nil+}++// remoteAccessToken returns a usable access token for an account, refreshing+// it when it is about to expire. stale is a token the app just rejected;+// passing it forces a refresh unless another call already replaced it. A+// refresh the server refuses marks the account expired and returns+// ErrAccountMissing, so the agent asks for a new connection.+func (s *Service) remoteAccessToken(ctx context.Context, id pgtype.UUID, stale string) (string, error) {+ row, err := s.q.GetRemoteAppConnection(ctx, id)+ if err != nil || row.Status != "active" {+ return "", ErrAccountMissing+ }+ if stale == "" && s.tokenFresh(row) {+ if token, err := s.open(row.AccessToken); err == nil && token != "" {+ return token, nil+ }+ }+ return s.refreshRemote(ctx, id, stale)+}++func (s *Service) tokenFresh(row db.RemoteAppConnection) bool {+ return len(row.AccessToken) > 0 && (!row.ExpiresAt.Valid || row.ExpiresAt.Time.After(s.now().Add(remoteRefreshSkew)))+}++func (s *Service) refreshRemote(ctx context.Context, id pgtype.UUID, stale string) (string, error) {+ tx, err := s.remote.db.Begin(ctx)+ if err != nil {+ return "", err+ }+ defer tx.Rollback(ctx)+ qtx := s.q.WithTx(tx)+ row, err := qtx.LockRemoteAppConnection(ctx, id)+ if err != nil || row.Status != "active" {+ return "", ErrAccountMissing+ }+ if current, err := s.open(row.AccessToken); err == nil && current != "" && current != stale && s.tokenFresh(row) {+ return current, tx.Commit(ctx)+ }+ expire := func(reason string) (string, error) {+ slog.InfoContext(ctx, "connectedapps: remote account sign-in expired",+ "connection_id", util.UUIDToString(row.ID), "app", row.AppSlug, "scope", row.Scope, "reason", reason)+ if err := qtx.SetRemoteAppConnectionStatus(ctx, db.SetRemoteAppConnectionStatusParams{ID: row.ID, Status: "expired"}); err != nil {+ return "", err+ }+ if err := tx.Commit(ctx); err != nil {+ return "", err+ }+ s.dropRemoteTools(row.ID)+ return "", ErrAccountMissing+ }+ refresh, err := s.open(row.RefreshToken)+ if err != nil || refresh == "" {+ return expire("no_refresh_token")+ }+ client, err := qtx.GetRemoteAppOAuthClientByID(ctx, row.OauthClientID)+ if err != nil {+ return expire("client_missing")+ }+ app, ok := s.RemoteApp(row.AppSlug)+ if !ok {+ return "", ErrAccountMissing+ }+ registration, err := s.registration(client)+ if err != nil {+ return "", err+ }+ // Refresh tokens are single-use: once the app has rotated it, the new pair+ // must be saved even if the caller has gone away.+ saveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), remoteRefreshTimeout)+ defer cancel()+ tokens, err := s.remote.upstream.Refresh(saveCtx, client.TokenEndpoint, app.Endpoint, refresh, registration)+ if err != nil {+ var oauthErr *remotemcp.OAuthError+ if errors.As(err, &oauthErr) && oauthErr.Rejected() {+ if oauthErr.Code == "invalid_client" {+ // Reconnecting would send the user to an authorize page that+ // rejects this client and never calls back; register anew.+ if err := qtx.DeleteRemoteAppOAuthClient(ctx, client.ID); err != nil {+ return "", err+ }+ }+ return expire("refresh_rejected")+ }+ return "", fmt.Errorf("connectedapps: refresh token: %w", err)+ }+ access, err := s.seal(tokens.AccessToken)+ if err != nil {+ return "", err+ }+ nextRefresh := row.RefreshToken+ if tokens.RefreshToken != "" {+ if nextRefresh, err = s.seal(tokens.RefreshToken); err != nil {+ return "", err+ }+ }+ if err := qtx.UpdateRemoteAppConnectionTokens(saveCtx, db.UpdateRemoteAppConnectionTokensParams{+ ID: row.ID, AccessToken: access, RefreshToken: nextRefresh, ExpiresAt: expiry(s.now(), tokens.ExpiresIn),+ }); err != nil {+ return "", err+ }+ if err := tx.Commit(saveCtx); err != nil {+ return "", err+ }+ return tokens.AccessToken, nil+}++// withRemoteToken runs fn with the account's access token. When the app+// rejects the token, it refreshes once and retries; a second rejection marks+// the account expired.+func (s *Service) withRemoteToken(ctx context.Context, acct account, fn func(token string) error) error {+ token, err := s.remoteAccessToken(ctx, acct.connectionID, "")+ if err != nil {+ return err+ }+ err = fn(token)+ if !unauthorized(err) {+ return err+ }+ if token, err = s.remoteAccessToken(ctx, acct.connectionID, token); err != nil {+ return err+ }+ err = fn(token)+ if unauthorized(err) {+ if setErr := s.q.SetRemoteAppConnectionStatus(ctx, db.SetRemoteAppConnectionStatusParams{ID: acct.connectionID, Status: "expired"}); setErr != nil {+ return setErr+ }+ s.dropRemoteTools(acct.connectionID)+ return ErrAccountMissing+ }+ return err+}++func unauthorized(err error) bool {+ var status *remotemcp.StatusError+ return errors.As(err, &status) && status.Code == http.StatusUnauthorized+}++// remoteTools lists an app's tools as the account sees them, cached briefly+// per account.+func (s *Service) remoteTools(ctx context.Context, app RemoteApp, acct account) ([]RemoteTool, error) {+ key := util.UUIDToString(acct.connectionID)+ s.remote.mu.Lock()+ cached, ok := s.remote.tools[key]+ s.remote.mu.Unlock()+ if ok && s.now().Sub(cached.at) < remoteToolCacheTTL {+ return cached.tools, nil+ }+ var raws []json.RawMessage+ err := s.withRemoteToken(ctx, acct, func(token string) error {+ var err error+ raws, err = s.remote.upstream.ListTools(ctx, app.Endpoint, token)+ return err+ })+ if err != nil {+ return nil, err+ }+ tools := make([]RemoteTool, 0, len(raws))+ for _, raw := range raws {+ var t struct {+ Name string `json:"name"`+ Description string `json:"description"`+ Annotations struct {+ ReadOnlyHint *bool `json:"readOnlyHint"`+ DestructiveHint *bool `json:"destructiveHint"`+ } `json:"annotations"`+ }+ if json.Unmarshal(raw, &t) != nil || strings.TrimSpace(t.Name) == "" {+ continue+ }+ tool := RemoteTool{Name: t.Name, Description: t.Description, Raw: raw}+ if t.Annotations.ReadOnlyHint != nil && *t.Annotations.ReadOnlyHint {+ tool.Tags = append(tool.Tags, "readOnlyHint")+ } else if t.Annotations.DestructiveHint != nil && *t.Annotations.DestructiveHint {+ tool.Tags = append(tool.Tags, "destructiveHint")+ }+ tools = append(tools, tool)+ }+ s.remote.mu.Lock()+ s.remote.tools[key] = remoteToolCache{at: s.now(), tools: tools}+ s.remote.mu.Unlock()+ return tools, nil+}++func (s *Service) dropRemoteTools(id pgtype.UUID) {+ if s.remote == nil {+ return+ }+ s.remote.mu.Lock()+ delete(s.remote.tools, util.UUIDToString(id))+ s.remote.mu.Unlock()+}++// ListRemoteTools lists a remote app's tools for the settings page, through+// the workspace's team account or else the viewer's own. ErrAccountMissing+// means neither is connected, so there is nothing to list yet.+func (s *Service) ListRemoteTools(ctx context.Context, workspaceID, viewer pgtype.UUID, slug string) ([]RemoteTool, error) {+ app, ok := s.RemoteApp(slug)+ if !ok {+ return nil, composiointeg.ErrToolkitNotSupported+ }+ acct, err := s.resolveRemoteAccount(ctx, workspaceID, viewer, app.Slug, ScopeTeam)+ if err != nil {+ acct, err = s.resolveRemoteAccount(ctx, workspaceID, viewer, app.Slug, ScopePersonal)+ }+ if err != nil {+ return nil, err+ }+ return s.remoteTools(ctx, app, acct)+}++func (s *Service) resolveRemoteAccount(ctx context.Context, workspaceID, triggeredBy pgtype.UUID, slug, scope string) (account, error) {+ owner := workspaceID+ if scope != ScopeTeam {+ if !triggeredBy.Valid {+ return account{}, ErrAccountMissing+ }+ owner = triggeredBy+ }+ row, err := s.q.GetActiveRemoteAppConnection(ctx, db.GetActiveRemoteAppConnectionParams{AppSlug: slug, Scope: scope, OwnerID: owner})+ if isNoRows(err) {+ return account{}, ErrAccountMissing+ }+ if err != nil {+ return account{}, err+ }+ acct := account{scope: scope, connectionID: row.ID, remote: true}+ if scope != ScopeTeam {+ acct.owner = triggeredBy+ }+ return acct, nil+}++// classifyRemote is classify for a remote tool: the workspace's correction,+// then the curated pin, the tool name's verb, and the server's annotations.+func (s *Service) classifyRemote(ctx context.Context, workspaceID pgtype.UUID, slug string, tool RemoteTool) string {+ class, err := s.q.GetAppToolClassOverride(ctx, db.GetAppToolClassOverrideParams{+ WorkspaceID: workspaceID, ToolkitSlug: NormalizeSlug(slug), ToolSlug: strings.ToUpper(tool.Name),+ })+ if err == nil {+ return class+ }+ return Classify(slug, tool.Name, tool.Tags)+}++func (s *Service) seal(value string) ([]byte, error) {+ if value == "" {+ return nil, nil+ }+ return s.remote.box.Seal([]byte(value))+}++func (s *Service) open(sealed []byte) (string, error) {+ if len(sealed) == 0 {+ return "", nil+ }+ plain, err := s.remote.box.Open(sealed)+ return string(plain), err+}++func (s *Service) sealState(st remoteState) (string, error) {+ raw, err := json.Marshal(st)+ if err != nil {+ return "", err+ }+ sealed, err := s.remote.box.Seal(raw)+ if err != nil {+ return "", err+ }+ return base64.RawURLEncoding.EncodeToString(sealed), nil+}++func (s *Service) openState(raw string) (remoteState, error) {+ sealed, err := base64.RawURLEncoding.DecodeString(raw)+ if err != nil {+ return remoteState{}, ErrRemoteState+ }+ plain, err := s.remote.box.Open(sealed)+ if err != nil {+ return remoteState{}, ErrRemoteState+ }+ var st remoteState+ if json.Unmarshal(plain, &st) != nil || s.now().Unix() > st.Exp {+ return remoteState{}, ErrRemoteState+ }+ return st, nil+}++func randomToken() (string, error) {+ b := make([]byte, 32)+ if _, err := rand.Read(b); err != nil {+ return "", err+ }+ return base64.RawURLEncoding.EncodeToString(b), nil+}++func expiry(now time.Time, expiresIn int64) pgtype.Timestamptz {+ at := remotemcp.OAuthExpiry(now, expiresIn)+ return pgtype.Timestamptz{Time: at, Valid: !at.IsZero()}+}diff --git a/server/internal/connectedapps/remote_gateway.go b/server/internal/connectedapps/remote_gateway.gonew file mode 100644index 0000000000..63bd31a178--- /dev/null+++ b/server/internal/connectedapps/remote_gateway.go@@ -0,0 +1,194 @@+package connectedapps++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "strings"++ "github.com/multica-ai/multica/server/internal/util"+)++// ServeRemoteApp is the MCP server a run sees for one remote app, under the+// app's own name. Tools keep the names and schemas the app's server gives+// them; every call still goes through the account, rules, rate limit and+// activity log of the meta gateway before Multica forwards it with the+// account's token.+func (s *Service) ServeRemoteApp(w http.ResponseWriter, r *http.Request, slug string) {+ app, ok := s.RemoteApp(slug)+ if !ok {+ http.NotFound(w, r)+ return+ }+ s.serveRPC(w, r, func(ctx context.Context, rn *run, req rpcRequest) (rpcResponse, bool) {+ return s.dispatchRemote(ctx, rn, app, req)+ })+}++func (s *Service) dispatchRemote(ctx context.Context, rn *run, app RemoteApp, req rpcRequest) (rpcResponse, bool) {+ resp := rpcResponse{JSONRPC: "2.0", ID: req.ID}+ notification := len(req.ID) == 0 || string(req.ID) == "null"+ switch req.Method {+ case "initialize":+ var p struct {+ ProtocolVersion string `json:"protocolVersion"`+ }+ _ = json.Unmarshal(req.Params, &p)+ version := p.ProtocolVersion+ if version == "" {+ version = mcpVersion+ }+ resp.Result = map[string]any{+ "protocolVersion": version,+ "capabilities": map[string]any{"tools": map[string]any{}},+ "serverInfo": map[string]any{"name": app.Slug, "version": "1"},+ "instructions": fmt.Sprintf("%s tools, run through Multica with the account and permissions set there. "++ "If a call says the account is not connected, call %s on the %s server and end your turn.",+ app.Name, toolRequestConnection, GatewayServerName),+ }+ case "ping":+ resp.Result = map[string]any{}+ case "tools/list":+ resp.Result = map[string]any{"tools": s.remoteToolList(ctx, rn, app)}+ case "tools/call":+ var p struct {+ Name string `json:"name"`+ Arguments map[string]any `json:"arguments"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &rpcError{Code: -32602, Message: "invalid params"}+ break+ }+ resp.Result = s.remoteRun(ctx, rn, app, p.Name, p.Arguments)+ default:+ if strings.HasPrefix(req.Method, "notifications/") {+ return resp, true+ }+ resp.Error = &rpcError{Code: -32601, Message: "method not found"}+ }+ return resp, notification+}++// remoteToolList is the app's tools this run may call: none when the agent+// lacks the app or the account is not connected, and never a tool whose+// class the rules block.+func (s *Service) remoteToolList(ctx context.Context, rn *run, app RemoteApp) []json.RawMessage {+ out := []json.RawMessage{}+ agentApp, ok := rn.apps[app.Slug]+ if !ok {+ return out+ }+ acct, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, app.Slug, agentApp.AccountScope)+ if err != nil {+ return out+ }+ tools, err := s.remoteTools(ctx, app, acct)+ if err != nil {+ if !errors.Is(err, ErrAccountMissing) {+ slog.WarnContext(ctx, "connectedapps: list remote tools failed", "app", app.Slug, "task_id", util.UUIDToString(rn.task.ID))+ }+ return out+ }+ policies := map[string]string{}+ for _, tool := range tools {+ class := s.classifyRemote(ctx, rn.workspaceID, app.Slug, tool)+ policy, ok := policies[class]+ if !ok {+ if policy, _, err = s.policyFor(ctx, rn, agentApp, class); err != nil {+ policy = PolicyBlock+ }+ policies[class] = policy+ }+ if policy != PolicyBlock {+ out = append(out, tool.Raw)+ }+ }+ return out+}++func (s *Service) remoteRun(ctx context.Context, rn *run, app RemoteApp, name string, args map[string]any) any {+ agentApp, ok := rn.apps[app.Slug]+ if !ok {+ return textResult(fmt.Sprintf("%s is not available to you in this run", app.Name), true)+ }+ notConnected := textResult(fmt.Sprintf("the %s account for %s is not connected. Call %s on the %s server to ask for it, then end your turn.",+ agentApp.AccountScope, app.Slug, toolRequestConnection, GatewayServerName), true)+ acct, err := s.resolveAccount(ctx, rn.workspaceID, rn.triggeredBy, app.Slug, agentApp.AccountScope)+ if errors.Is(err, ErrAccountMissing) {+ return notConnected+ }+ if err != nil {+ return textResult("could not resolve the account for this app", true)+ }+ tools, err := s.remoteTools(ctx, app, acct)+ if errors.Is(err, ErrAccountMissing) {+ return notConnected+ }+ if err != nil {+ return textResult(fmt.Sprintf("could not reach %s right now; try again later", app.Name), true)+ }+ var tool *RemoteTool+ for i := range tools {+ if tools[i].Name == name {+ tool = &tools[i]+ break+ }+ }+ if tool == nil {+ return textResult(fmt.Sprintf("%s has no tool named %q", app.Name, name), true)+ }+ class := ClassifyCall(s.classifyRemote(ctx, rn.workspaceID, app.Slug, *tool), tool.Name, args)+ call := toolCall{+ workspaceID: rn.workspaceID, taskID: rn.task.ID, agentID: rn.agent.ID,+ issueID: rn.task.IssueID, chatSessionID: rn.task.ChatSessionID, triggeredBy: rn.triggeredBy,+ toolkit: app.Slug, tool: tool.Name, class: class,+ }+ policy, acct, err := s.policyFor(ctx, rn, agentApp, class)+ call.acct = acct+ if errors.Is(err, ErrAccountMissing) {+ return notConnected+ }+ if err != nil {+ return textResult("could not resolve the account for this app", true)+ }+ if refusal := s.refuseCall(ctx, rn, agentApp, &call, policy); refusal != nil {+ return refusal+ }+ var result json.RawMessage+ err = s.withRemoteToken(ctx, acct, func(token string) error {+ var err error+ result, err = s.remote.upstream.CallTool(ctx, app.Endpoint, token, tool.Name, args)+ return err+ })+ s.touch(ctx, rn.workspaceID, acct)+ if errors.Is(err, ErrAccountMissing) {+ call.outcome, call.err = "error", "sign-in expired"+ s.recordCall(ctx, call)+ return textResult(fmt.Sprintf("the %s sign-in for this account expired. Call %s on the %s server to ask for a new connection, then end your turn.",+ app.Name, toolRequestConnection, GatewayServerName), true)+ }+ if err != nil {+ call.outcome, call.err = "error", truncate(err.Error(), 500)+ logExecutionFailure(ctx, call, "request_failed")+ s.recordCall(ctx, call)+ return textResult("the app call failed: "+truncate(err.Error(), 500), true)+ }+ var outcome struct {+ IsError bool `json:"isError"`+ }+ _ = json.Unmarshal(result, &outcome)+ call.outcome = "ok"+ if outcome.IsError {+ call.outcome, call.err = "error", "the tool returned an error"+ logExecutionFailure(ctx, call, "tool_unsuccessful")+ }+ s.recordCall(ctx, call)+ return result+}++func remoteServerHint(app RemoteApp) map[string]any {+ return textResult(fmt.Sprintf("%s tools are on the MCP server %q. Call them there directly; they are not run through apps_run_tool.", app.Name, app.Slug), true)+}diff --git a/server/internal/connectedapps/service.go b/server/internal/connectedapps/service.goindex 9461b5768b..dc2e003114 100644--- a/server/internal/connectedapps/service.go+++ b/server/internal/connectedapps/service.go@@ -87,6 +87,14 @@ type Config struct {// CallsPerMinute caps the calls one account runs per minute;// DefaultCallsPerMinute when zero.CallsPerMinute int+ // SecretBox seals remote app tokens at rest and DB runs their refresh.+ // Remote MCP apps are off unless both are set.+ SecretBox Sealer+ DB TxStarter+ // RemoteApps overrides BuiltinRemoteApps; RemoteUpstream overrides the+ // network client. Both are for tests.+ RemoteApps []RemoteApp+ RemoteUpstream RemoteUpstream}// Service is the connected-apps runtime: overlay, gateway, and confirmations.@@ -99,6 +107,7 @@ type Service struct {now func() time.Timeresumer ResumerperMinute int+ remote *remoteSupport}// New returns a Service, or an error when a required dependency is missing.@@ -129,6 +138,7 @@ func New(cfg Config) (*Service, error) {bus: cfg.Bus,now: now,perMinute: perMinute,+ remote: newRemoteSupport(cfg, base),}, nil}@@ -235,13 +245,26 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.return runtimeapps.MCPOverlayResult{}, err}}+ servers := map[string]gatewayServer{GatewayServerName: {Type: "http", URL: s.gatewayURL}}meta := make([]runtimeapps.ConnectedApp, 0, len(apps))for _, app := range apps {if !catalog.Allows(app.ToolkitSlug) {continue}+ slug := NormalizeSlug(app.ToolkitSlug)+ provider, serverName, name := Provider, GatewayServerName, runtimeapps.DisplayNameForToolkitSlug(slug)status := "not_connected"- if app.AccountScope == ScopeTeam {+ if remote, ok := s.RemoteApp(slug); ok {+ // A remote app is mounted as its own MCP server named after+ // the app, so its tools keep their names and schemas. The+ // entry replaces a same-named server from the runtime's local+ // config for this run.+ provider, serverName, name = RemoteProvider, remote.Slug, remote.Name+ servers[remote.Slug] = gatewayServer{Type: "http", URL: s.remoteGatewayURL(remote.Slug)}+ if _, err := s.resolveRemoteAccount(ctx, agent.WorkspaceID, originatorUserID, slug, app.AccountScope); err == nil {+ status = "connected"+ }+ } else if app.AccountScope == ScopeTeam {if _, ok := team[app.ToolkitSlug]; ok {status = "connected"}@@ -253,10 +276,10 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.level = LevelWrite}meta = append(meta, runtimeapps.ConnectedApp{- Provider: Provider,- ServerName: GatewayServerName,+ Provider: provider,+ ServerName: serverName,ToolkitSlug: app.ToolkitSlug,- ToolkitName: runtimeapps.DisplayNameForToolkitSlug(app.ToolkitSlug),+ ToolkitName: name,AccountScope: app.AccountScope,Level: level,AccountStatus: status,@@ -265,17 +288,20 @@ func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.if len(meta) == 0 {return runtimeapps.MCPOverlayResult{}, nil}- raw, err := json.Marshal(gatewayOverlay{MCPServers: map[string]gatewayServer{- GatewayServerName: {Type: "http", URL: s.gatewayURL},- }})+ raw, err := json.Marshal(gatewayOverlay{MCPServers: servers})if err != nil {return runtimeapps.MCPOverlayResult{}, err}return runtimeapps.MCPOverlayResult{MCPOverlay: raw, ConnectedApps: meta}, nil}-// AuthorizeOverlay adds a token for taskID to the gateway entry of a stored-// overlay. Overlays without a gateway entry are returned unchanged.+func (s *Service) remoteGatewayURL(slug string) string {+ return s.gatewayURL + "/" + slug+}++// AuthorizeOverlay adds a token for taskID to every gateway entry of a stored+// overlay: the meta gateway and each remote app's server. Overlays without a+// gateway entry are returned unchanged.func (s *Service) AuthorizeOverlay(overlay []byte, taskID pgtype.UUID) ([]byte, error) {var parsed struct {MCPServers map[string]json.RawMessage `json:"mcpServers"`@@ -283,26 +309,30 @@ func (s *Service) AuthorizeOverlay(overlay []byte, taskID pgtype.UUID) ([]byte,if err := json.Unmarshal(overlay, &parsed); err != nil {return nil, err}- entry, ok := parsed.MCPServers[GatewayServerName]- if !ok {+ if _, ok := parsed.MCPServers[GatewayServerName]; !ok {return overlay, nil}- var server gatewayServer- if err := json.Unmarshal(entry, &server); err != nil {- return nil, err- }token, err := SignTaskToken(s.secret, util.UUIDToString(taskID), s.now().Add(tokenTTL))if err != nil {return nil, err}- server.Type = "http"- server.URL = s.gatewayURL- server.Headers = map[string]string{"Authorization": "Bearer " + token}- raw, err := json.Marshal(server)- if err != nil {- return nil, err+ for name, entry := range parsed.MCPServers {+ url := s.gatewayURL+ if name != GatewayServerName {+ var server gatewayServer+ if err := json.Unmarshal(entry, &server); err != nil || server.URL != s.remoteGatewayURL(name) {+ continue+ }+ url = server.URL+ }+ raw, err := json.Marshal(gatewayServer{+ Type: "http", URL: url, Headers: map[string]string{"Authorization": "Bearer " + token},+ })+ if err != nil {+ return nil, err+ }+ parsed.MCPServers[name] = raw}- parsed.MCPServers[GatewayServerName] = rawreturn json.Marshal(map[string]any{"mcpServers": parsed.MCPServers})}@@ -347,11 +377,17 @@ type account struct {connectionID pgtype.UUID// owner is the member whose personal account it is; invalid for team.owner pgtype.UUID+ // remote marks a remote MCP app account; connectionID is then a+ // remote_app_connection row.+ remote bool}// resolveAccount finds the account an app acts as for a run: the workspace's// team account, or the personal account of the member who triggered the run.func (s *Service) resolveAccount(ctx context.Context, workspaceID, triggeredBy pgtype.UUID, slug, scope string) (account, error) {+ if _, ok := s.RemoteApp(slug); ok {+ return s.resolveRemoteAccount(ctx, workspaceID, triggeredBy, NormalizeSlug(slug), scope)+ }if scope == ScopeTeam {team, err := s.activeTeamAccounts(ctx, workspaceID)if err != nil {@@ -396,6 +432,10 @@ func (s *Service) accountRule(ctx context.Context, workspaceID pgtype.UUID, slug}func (s *Service) touch(ctx context.Context, workspaceID pgtype.UUID, acct account) {+ if acct.remote {+ _ = s.q.TouchRemoteAppConnection(ctx, acct.connectionID)+ return+ }if acct.scope == ScopeTeam {_ = s.q.TouchWorkspaceComposioConnection(ctx, db.TouchWorkspaceComposioConnectionParams{ID: acct.connectionID, WorkspaceID: workspaceID})returndiff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 5c6c6dea67..0ffc45a19e 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -171,6 +171,7 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {var b strings.Buildervar lines strings.Buildergateway := ""+ remote := falsefor _, app := range apps {serverName := sanitizeBriefCodeToken(app.ServerName)toolkitSlug := sanitizeBriefCodeToken(app.ToolkitSlug)@@ -189,6 +190,13 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`%s\n", name, toolkitSlug, serverName, gatewayAppDetail(app))continue}+ if app.Provider == "multica_remote" {+ // Served by Multica under the app's own server name: its tools+ // are called directly, not through the apps_* meta tools.+ remote = true+ fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`%s\n", name, toolkitSlug, serverName, gatewayAppDetail(app))+ continue+ }fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`\n", name, toolkitSlug, serverName)}if lines.Len() == 0 {@@ -202,6 +210,10 @@ func BuildConnectedAppsBlock(apps []runtimeapps.ConnectedApp) string {"Allowed calls run immediately and return their result. Never work around a blocked call. "+"For a `not connected` account, call `apps_request_connection` and end your turn.\n", gateway)}+ if remote {+ b.WriteString("Call the tools of an app on its own MCP server directly. " ++ "For a `not connected` account, call `apps_request_connection` on `multica_apps` and end your turn.\n")+ }b.WriteString("\n")return b.String()}diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 00a021ecaf..8c54fef9c9 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -887,6 +887,26 @@ func TestConnectedAppsBlockLivesOutsideBrief(t *testing.T) {}}+func TestConnectedAppsBlockRemoteAppUsesItsOwnServer(t *testing.T) {+ t.Parallel()+ block := BuildConnectedAppsBlock([]runtimeapps.ConnectedApp{{+ Provider: "multica_remote", ServerName: "mobbin", ToolkitSlug: "mobbin", ToolkitName: "Mobbin",+ AccountScope: "personal", Level: "read", AccountStatus: "not_connected",+ }})+ for _, want := range []string{+ "- Mobbin (`mobbin`) via MCP server `mobbin` — account of the person who triggered this run, read only, not connected",+ "Call the tools of an app on its own MCP server directly.",+ "call `apps_request_connection` on `multica_apps`",+ } {+ if !strings.Contains(block, want) {+ t.Errorf("missing %q in\n%s", want, block)+ }+ }+ if strings.Contains(block, "apps_run_tool") {+ t.Errorf("a remote app alone must not point at apps_run_tool:\n%s", block)+ }+}+func TestConnectedAppsBlockRunsDirectly(t *testing.T) {t.Parallel()for _, level := range []string{"write", "confirm_writes"} {diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.goindex f5139d2ddc..9aab1529c6 100644--- a/server/internal/handler/connected_apps.go+++ b/server/internal/handler/connected_apps.go@@ -222,16 +222,40 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list personal accounts")return}+ remoteTeam, err := h.remoteConnections(r, connectedapps.ScopeTeam, workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list team accounts")+ return+ }+ remotePersonal, err := h.remoteConnections(r, connectedapps.ScopePersonal, member.UserID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list personal accounts")+ return+ }agentApps, err := h.Queries.ListAgentAppsInWorkspace(ctx, workspaceID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list agent apps")return}- slugs := make([]string, 0, len(team)+len(personal))+ teamRows := make([]AppConnectionResponse, 0, len(team)+len(remoteTeam))for _, row := range team {- slugs = append(slugs, row.ToolkitSlug)+ teamRows = append(teamRows, connectionFromTeam(row))}+ for _, row := range remoteTeam {+ teamRows = append(teamRows, connectionFromRemote(row))+ }+ personalRows := make([]AppConnectionResponse, 0, len(personal)+len(remotePersonal))for _, row := range personal {+ personalRows = append(personalRows, connectionFromPersonal(row))+ }+ for _, row := range remotePersonal {+ personalRows = append(personalRows, connectionFromRemote(row))+ }+ slugs := make([]string, 0, len(teamRows)+len(personalRows))+ for _, row := range teamRows {+ slugs = append(slugs, row.ToolkitSlug)+ }+ for _, row := range personalRows {slugs = append(slugs, row.ToolkitSlug)}rules, err := h.Queries.ListAppActionRulesForRun(ctx, db.ListAppActionRulesForRunParams{@@ -252,18 +276,16 @@ func (h *Handler) GetAppsOverview(w http.ResponseWriter, r *http.Request) {CatalogMode: catalog.Mode,AllowedToolkits: append([]string{}, catalog.Allowed...),CanManage: isAdmin,- Team: make([]AppConnectionResponse, 0, len(team)),- Personal: make([]AppConnectionResponse, 0, len(personal)),+ Team: make([]AppConnectionResponse, 0, len(teamRows)),+ Personal: make([]AppConnectionResponse, 0, len(personalRows)),AgentApps: make([]AgentAppResponse, 0, len(agentApps)),}- for _, row := range team {- connection := connectionFromTeam(row)- connection.ActionsBlocked = blocked[uuidToString(pgtype.UUID{})+":"+row.ToolkitSlug]+ for _, connection := range teamRows {+ connection.ActionsBlocked = blocked[uuidToString(pgtype.UUID{})+":"+connection.ToolkitSlug]resp.Team = append(resp.Team, connection)}- for _, row := range personal {- connection := connectionFromPersonal(row)- connection.ActionsBlocked = blocked[uuidToString(member.UserID)+":"+row.ToolkitSlug]+ for _, connection := range personalRows {+ connection.ActionsBlocked = blocked[uuidToString(member.UserID)+":"+connection.ToolkitSlug]resp.Personal = append(resp.Personal, connection)}for _, row := range agentApps {@@ -291,9 +313,24 @@ func (h *Handler) ListAppCatalog(w http.ResponseWriter, r *http.Request) {return}catalog := h.ConnectedApps.Catalog(r.Context(), workspaceID)- out := make([]AppCatalogEntry, 0, len(toolkits))+ remoteApps := h.ConnectedApps.RemoteApps()+ out := make([]AppCatalogEntry, 0, len(remoteApps)+len(toolkits))+ for _, app := range remoteApps {+ allowed := catalog.Allows(app.Slug)+ if !allowed && !viewAll {+ continue+ }+ entry := AppCatalogEntry{Slug: app.Slug, Name: app.Name, Category: app.Category, Allowed: allowed}+ if curated, ok := connectedapps.Curated(app.Slug); ok {+ entry.Curated, entry.RecommendedScope = true, curated.Scope+ }+ out = append(out, entry)+ }for _, tk := range toolkits {slug := connectedapps.NormalizeSlug(tk.Slug)+ if _, remote := h.ConnectedApps.RemoteApp(slug); remote {+ continue+ }allowed := catalog.Allows(slug)if !allowed && !viewAll {continue@@ -378,7 +415,13 @@ func (h *Handler) ConnectTeamApp(w http.ResponseWriter, r *http.Request) {}}}- url, err := h.Composio.BeginTeamConnect(r.Context(), workspaceID, member.UserID, req.ToolkitSlug, req.ReturnTo)+ var url string+ var err error+ if _, remote := h.ConnectedApps.RemoteApp(req.ToolkitSlug); remote {+ url, err = h.ConnectedApps.BeginRemoteConnect(r.Context(), req.ToolkitSlug, connectedapps.ScopeTeam, workspaceID, member.UserID, req.ReturnTo)+ } else {+ url, err = h.Composio.BeginTeamConnect(r.Context(), workspaceID, member.UserID, req.ToolkitSlug, req.ReturnTo)+ }if err != nil {writeConnectError(w, r, err)return@@ -400,7 +443,13 @@ func (h *Handler) ConnectPersonalApp(w http.ResponseWriter, r *http.Request) {if !ok {return}- url, err := h.Composio.BeginConnectReturning(r.Context(), member.UserID, req.ToolkitSlug, req.ReturnTo)+ var url string+ var err error+ if _, remote := h.ConnectedApps.RemoteApp(req.ToolkitSlug); remote {+ url, err = h.ConnectedApps.BeginRemoteConnect(r.Context(), req.ToolkitSlug, connectedapps.ScopePersonal, member.UserID, member.UserID, req.ReturnTo)+ } else {+ url, err = h.Composio.BeginConnectReturning(r.Context(), member.UserID, req.ToolkitSlug, req.ReturnTo)+ }if err != nil {writeConnectError(w, r, err)return@@ -426,7 +475,15 @@ func (h *Handler) DisconnectTeamApp(w http.ResponseWriter, r *http.Request) {if !ok {return}+ slug := ""row, err := h.Composio.DisconnectTeam(r.Context(), workspaceID, id)+ if errors.Is(err, composio.ErrConnectionNotFound) {+ var remoteRow db.RemoteAppConnection+ remoteRow, err = h.ConnectedApps.DisconnectRemote(r.Context(), id, connectedapps.ScopeTeam, workspaceID)+ slug = remoteRow.AppSlug+ } else {+ slug = row.ToolkitSlug+ }if errors.Is(err, composio.ErrConnectionNotFound) {writeError(w, http.StatusNotFound, "connection not found")return@@ -436,7 +493,7 @@ func (h *Handler) DisconnectTeamApp(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadGateway, "failed to disconnect")return}- h.ConnectedApps.CancelTeamRequests(r.Context(), workspaceID, row.ToolkitSlug)+ h.ConnectedApps.CancelTeamRequests(r.Context(), workspaceID, slug)w.WriteHeader(http.StatusNoContent)}@@ -741,7 +798,7 @@ func (h *Handler) ListAppTools(w http.ResponseWriter, r *http.Request) {if !h.appsReady(w, r) {return}- _, workspaceID, _, ok := h.appsMember(w, r)+ member, workspaceID, _, ok := h.appsMember(w, r)if !ok {return}@@ -750,6 +807,10 @@ func (h *Handler) ListAppTools(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "toolkit_slug is required")return}+ if _, remote := h.ConnectedApps.RemoteApp(slug); remote {+ h.listRemoteAppTools(w, r, workspaceID, member.UserID, slug)+ return+ }tools, err := h.Composio.ListToolkitTools(r.Context(), slug)if err != nil {slog.Warn("apps tools failed", append(logger.RequestAttrs(r), "error", err)...)diff --git a/server/internal/handler/connected_apps_remote.go b/server/internal/handler/connected_apps_remote.gonew file mode 100644index 0000000000..d389158c79--- /dev/null+++ b/server/internal/handler/connected_apps_remote.go@@ -0,0 +1,116 @@+package handler++import (+ "errors"+ "log/slog"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/integrations/composio"+ "github.com/multica-ai/multica/server/internal/logger"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Remote MCP apps (MUL-9792): apps such as Mobbin whose own MCP server+// Multica connects to over OAuth. They sit in the same catalog, accounts and+// agent apps as Composio apps; only connecting and executing differ.++// AppsRemoteGateway (POST /api/apps/mcp/{app}) is the MCP server a run sees+// for one remote app. It authenticates like AppsGateway.+func (h *Handler) AppsRemoteGateway(w http.ResponseWriter, r *http.Request) {+ if h.ConnectedApps == nil || !h.composioMCPAppsEnabled(r.Context()) {+ http.Error(w, "connected apps are not configured", http.StatusServiceUnavailable)+ return+ }+ h.ConnectedApps.ServeRemoteApp(w, r, chi.URLParam(r, "app"))+}++// AppsOAuthCallback (GET /api/apps/oauth/callback) is where a remote app's+// authorization server sends the browser back. It is public: the sealed state+// names who started the handshake. Like the Composio callback, every failure+// collapses to one generic redirect.+func (h *Handler) AppsOAuthCallback(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || h.ConnectedApps == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeFeatureDisabled(w, "apps_not_configured", "connected apps are not configured")+ return+ }+ q := r.URL.Query()+ result, err := h.ConnectedApps.CompleteRemoteConnect(r.Context(), q.Get("state"), q.Get("code"), q.Get("error"))+ redirect := composio.CallbackResult{ToolkitSlug: result.Slug, ReturnTo: result.ReturnTo}+ if result.Scope == connectedapps.ScopeTeam {+ redirect.WorkspaceID = uuidToString(result.Owner)+ } else if result.Owner.Valid {+ redirect.UserID = uuidToString(result.Owner)+ }+ if errors.Is(err, composio.ErrTeamConnectRefused) {+ http.Redirect(w, r, h.Composio.CallbackRedirectFailure(redirect, composio.CallbackFeatureLockedReason), http.StatusFound)+ return+ }+ if err != nil {+ if !errors.Is(err, connectedapps.ErrRemoteState) {+ slog.Warn("apps remote connect failed", append(logger.RequestAttrs(r), "app", result.Slug, "error", err)...)+ }+ http.Redirect(w, r, h.Composio.CallbackRedirect(redirect, false), http.StatusFound)+ return+ }+ if result.Scope == connectedapps.ScopePersonal {+ h.ConnectedApps.ResolveConnectRequests(r.Context(), result.Owner, result.Slug)+ }+ http.Redirect(w, r, h.Composio.CallbackRedirect(redirect, true), http.StatusFound)+}++// listRemoteAppTools is ListAppTools for a remote app. Its tools come from the+// app's server, so they are listed through the team account or the viewer's+// own; with neither connected the list is empty.+func (h *Handler) listRemoteAppTools(w http.ResponseWriter, r *http.Request, workspaceID, viewer pgtype.UUID, slug string) {+ tools, err := h.ConnectedApps.ListRemoteTools(r.Context(), workspaceID, viewer, slug)+ if errors.Is(err, connectedapps.ErrAccountMissing) {+ writeJSON(w, http.StatusOK, map[string]any{"tools": []AppToolResponse{}})+ return+ }+ if err != nil {+ slog.Warn("apps remote tools failed", append(logger.RequestAttrs(r), "app", slug, "error", err)...)+ writeError(w, http.StatusBadGateway, "failed to load tools")+ return+ }+ overrides := h.ConnectedApps.ClassOverrides(r.Context(), workspaceID, slug)+ out := make([]AppToolResponse, 0, len(tools))+ for _, t := range tools {+ auto := connectedapps.Classify(slug, t.Name, t.Tags)+ class, overridden := overrides[strings.ToUpper(t.Name)]+ if !overridden {+ class = auto+ }+ out = append(out, AppToolResponse{+ Slug: t.Name, Name: t.Name, Description: t.Description,+ AutoClass: auto, Class: class, Overridden: overridden,+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"tools": out})+}++func connectionFromRemote(row db.RemoteAppConnection) AppConnectionResponse {+ conn := AppConnectionResponse{+ ID: uuidToString(row.ID),+ ToolkitSlug: row.AppSlug,+ Status: row.Status,+ ConnectedAt: timestampToString(row.ConnectedAt),+ LastUsedAt: timestampToPtr(row.LastUsedAt),+ }+ if row.Scope == connectedapps.ScopeTeam {+ conn.ConnectedBy = uuidToPtr(row.ConnectedBy)+ }+ return conn+}++// remoteConnections lists an owner's remote app accounts, or none when remote+// apps are off.+func (h *Handler) remoteConnections(r *http.Request, scope string, owner pgtype.UUID) ([]db.RemoteAppConnection, error) {+ if len(h.ConnectedApps.RemoteApps()) == 0 {+ return nil, nil+ }+ return h.Queries.ListRemoteAppConnectionsForOwner(r.Context(), db.ListRemoteAppConnectionsForOwnerParams{Scope: scope, OwnerID: owner})+}diff --git a/server/internal/handler/connected_apps_remote_test.go b/server/internal/handler/connected_apps_remote_test.gonew file mode 100644index 0000000000..9ef8dde367--- /dev/null+++ b/server/internal/handler/connected_apps_remote_test.go@@ -0,0 +1,505 @@+package handler++import (+ "bytes"+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ "github.com/multica-ai/multica/server/pkg/remotemcp"+)++const remoteTestBase = "https://api.multica.test"++// remoteFakeUpstream is a remote MCP app and its authorization server.+type remoteFakeUpstream struct {+ mu sync.Mutex+ verifiers []string+ refreshed []string+ calls []string+ tokens []string+ issued int+ refreshErr error+ rejectTokenOf string+ registered int+ onRefresh func()+}++func (f *remoteFakeUpstream) DiscoverOAuth(context.Context, string) (remotemcp.OAuthMetadata, error) {+ return remotemcp.OAuthMetadata{+ ResourceEndpoint: "https://api.mobbin.com/mcp",+ AuthorizationEndpoint: "https://auth.mobbin.test/authorize",+ TokenEndpoint: "https://auth.mobbin.test/token",+ RegistrationEndpoint: "https://auth.mobbin.test/register",+ Scopes: []string{"openid"},+ }, nil+}++func (f *remoteFakeUpstream) Register(context.Context, remotemcp.OAuthMetadata, string) (remotemcp.OAuthClientRegistration, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.registered+++ return remotemcp.OAuthClientRegistration{ClientID: "client-1", TokenEndpointAuthMethod: "none"}, nil+}++func (f *remoteFakeUpstream) issue() remotemcp.OAuthTokenResponse {+ f.issued+++ n := string(rune('0' + f.issued))+ return remotemcp.OAuthTokenResponse{AccessToken: "access-" + n, RefreshToken: "refresh-" + n, ExpiresIn: 3600, TokenType: "Bearer"}+}++func (f *remoteFakeUpstream) Exchange(_ context.Context, _, _, code, _, verifier string, _ remotemcp.OAuthClientRegistration) (remotemcp.OAuthTokenResponse, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.verifiers = append(f.verifiers, verifier)+ return f.issue(), nil+}++func (f *remoteFakeUpstream) Refresh(_ context.Context, _, _, refreshToken string, _ remotemcp.OAuthClientRegistration) (remotemcp.OAuthTokenResponse, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.refreshed = append(f.refreshed, refreshToken)+ if f.onRefresh != nil {+ f.onRefresh()+ }+ if f.refreshErr != nil {+ return remotemcp.OAuthTokenResponse{}, f.refreshErr+ }+ return f.issue(), nil+}++func (f *remoteFakeUpstream) ListTools(_ context.Context, _, token string) ([]json.RawMessage, error) {+ return []json.RawMessage{+ json.RawMessage(`{"name":"search_screens","description":"Search app screens","inputSchema":{"type":"object"},"annotations":{"readOnlyHint":true}}`),+ json.RawMessage(`{"name":"save_screen","description":"Save a screen to a collection","inputSchema":{"type":"object"}}`),+ }, nil+}++func (f *remoteFakeUpstream) CallTool(_ context.Context, _, token, name string, _ map[string]any) (json.RawMessage, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.calls = append(f.calls, name)+ f.tokens = append(f.tokens, token)+ if f.rejectTokenOf != "" && token == f.rejectTokenOf {+ return nil, &remotemcp.StatusError{Code: http.StatusUnauthorized}+ }+ return json.RawMessage(`{"content":[{"type":"image","data":"AAA","mimeType":"image/png"}]}`), nil+}++type remoteAppsFixture struct {+ *appsFixture+ up *remoteFakeUpstream+}++func newRemoteAppsFixture(t *testing.T) *remoteAppsFixture {+ t.Helper()+ f := newAppsFixture(t)+ box, err := secretbox.New(bytes.Repeat([]byte{7}, secretbox.KeySize))+ if err != nil {+ t.Fatal(err)+ }+ up := &remoteFakeUpstream{}+ apps, err := connectedapps.New(connectedapps.Config{+ Queries: f.h.Queries,+ Composio: f.h.Composio,+ TokenSecret: connectedapps.DeriveTokenSecret([]byte("apps-test-secret")),+ PublicBaseURL: remoteTestBase,+ SecretBox: box,+ DB: testPool,+ RemoteUpstream: up,+ })+ if err != nil {+ t.Fatal(err)+ }+ apps.SetResumer(f.h)+ apps.SetTeamConnectGate(f.h.TeamAppConnectGate)+ f.h.ConnectedApps = apps+ t.Cleanup(func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM remote_app_connection WHERE owner_id = ANY($1::uuid[])`, []string{testUserID, testWorkspaceID, f.member})+ testPool.Exec(ctx, `DELETE FROM remote_app_oauth_client WHERE redirect_uri = $1`, remoteTestBase+connectedapps.RemoteCallbackPath)+ })+ return &remoteAppsFixture{appsFixture: f, up: up}+}++// connect runs the personal connect handshake for userID and returns the+// callback's redirect.+func (f *remoteAppsFixture) connect(t *testing.T, userID string) string {+ t.Helper()+ w := httptest.NewRecorder()+ f.h.ConnectPersonalApp(w, appsReqAs(t, userID, http.MethodPost, "/api/apps/personal/connect", map[string]string{"toolkit_slug": "mobbin"}))+ if w.Code != http.StatusOK {+ t.Fatalf("connect: %d %s", w.Code, w.Body.String())+ }+ var init ComposioConnectInitResponse+ json.Unmarshal(w.Body.Bytes(), &init)+ authorize, err := url.Parse(init.RedirectURL)+ if err != nil || authorize.Host != "auth.mobbin.test" {+ t.Fatalf("redirect_url = %q", init.RedirectURL)+ }+ q := authorize.Query()+ if q.Get("client_id") != "client-1" || q.Get("resource") != "https://api.mobbin.com/mcp" ||+ q.Get("redirect_uri") != remoteTestBase+connectedapps.RemoteCallbackPath || q.Get("scope") != "openid" {+ t.Fatalf("authorize query = %v", q)+ }+ code := f.callback(t, "state="+url.QueryEscape(q.Get("state"))+"&code=auth-code")+ f.up.mu.Lock()+ verifier := f.up.verifiers[len(f.up.verifiers)-1]+ f.up.mu.Unlock()+ sum := sha256.Sum256([]byte(verifier))+ if base64.RawURLEncoding.EncodeToString(sum[:]) != q.Get("code_challenge") {+ t.Fatal("the code exchange did not use the verifier behind the PKCE challenge")+ }+ return code+}++func (f *remoteAppsFixture) callback(t *testing.T, rawQuery string) string {+ t.Helper()+ w := httptest.NewRecorder()+ f.h.AppsOAuthCallback(w, httptest.NewRequest(http.MethodGet, connectedapps.RemoteCallbackPath+"?"+rawQuery, nil))+ if w.Code != http.StatusFound {+ t.Fatalf("callback: %d %s", w.Code, w.Body.String())+ }+ return w.Header().Get("Location")+}++// remote sends one JSON-RPC request to the app's gateway server.+func (f *remoteAppsFixture) remote(t *testing.T, token, method string, params any) (int, json.RawMessage) {+ t.Helper()+ return f.remoteCtx(t, context.Background(), token, method, params)+}++func (f *remoteAppsFixture) remoteCtx(t *testing.T, ctx context.Context, token, method string, params any) (int, json.RawMessage) {+ t.Helper()+ body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})+ req := httptest.NewRequestWithContext(ctx, http.MethodPost, connectedapps.GatewayPath+"/mobbin", bytes.NewReader(body))+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ w := httptest.NewRecorder()+ f.h.AppsRemoteGateway(w, withURLParam(req, "app", "mobbin"))+ if w.Code != http.StatusOK {+ return w.Code, nil+ }+ var resp struct {+ Result json.RawMessage `json:"result"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode %s: %v", w.Body.String(), err)+ }+ return w.Code, resp.Result+}++func (f *remoteAppsFixture) toolNames(t *testing.T, token string) []string {+ t.Helper()+ _, raw := f.remote(t, token, "tools/list", map[string]any{})+ var result struct {+ Tools []struct {+ Name string `json:"name"`+ } `json:"tools"`+ }+ json.Unmarshal(raw, &result)+ names := []string{}+ for _, tool := range result.Tools {+ names = append(names, tool.Name)+ }+ return names+}++func (f *remoteAppsFixture) personalStatus(t *testing.T) string {+ t.Helper()+ var status string+ if err := testPool.QueryRow(context.Background(), `+ SELECT status FROM remote_app_connection WHERE app_slug = 'mobbin' AND scope = 'personal' AND owner_id = $1+ `, testUserID).Scan(&status); err != nil {+ return ""+ }+ return status+}++func TestRemoteApps_ConnectMountAndRun(t *testing.T) {+ f := newRemoteAppsFixture(t)++ w := httptest.NewRecorder()+ f.h.ListAppCatalog(w, appsReqAs(t, testUserID, http.MethodGet, "/api/apps/catalog", nil))+ var catalog struct {+ Apps []AppCatalogEntry `json:"apps"`+ }+ json.Unmarshal(w.Body.Bytes(), &catalog)+ if len(catalog.Apps) == 0 || catalog.Apps[0].Slug != "mobbin" || !catalog.Apps[0].Curated || catalog.Apps[0].RecommendedScope != "personal" {+ t.Fatalf("catalog = %+v", catalog.Apps)+ }++ if loc := f.connect(t, testUserID); !strings.Contains(loc, "tab=apps") || !strings.Contains(loc, "connected=mobbin") {+ t.Fatalf("callback redirect = %q", loc)+ }+ var sealed []byte+ testPool.QueryRow(context.Background(), `SELECT access_token FROM remote_app_connection WHERE owner_id = $1 AND app_slug = 'mobbin'`, testUserID).Scan(&sealed)+ if len(sealed) == 0 || bytes.Contains(sealed, []byte("access-")) {+ t.Fatal("the access token must be stored sealed")+ }++ w = httptest.NewRecorder()+ f.h.GetAppsOverview(w, appsReqAs(t, testUserID, http.MethodGet, "/api/apps", nil))+ var overview AppsOverviewResponse+ json.Unmarshal(w.Body.Bytes(), &overview)+ found := false+ for _, c := range overview.Personal {+ found = found || (c.ToolkitSlug == "mobbin" && c.Status == "active")+ }+ if !found {+ t.Fatalf("overview personal = %+v", overview.Personal)+ }++ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "mobbin", "account_scope": "personal", "level": "read"}}); w.Code != http.StatusOK {+ t.Fatalf("UpdateAgentApps: %d %s", w.Code, w.Body.String())+ }+ agent, _ := f.h.Queries.GetAgent(context.Background(), parseUUID(f.agentID))+ overlay, err := f.h.ConnectedApps.BuildTaskOverlay(context.Background(), parseUUID(testUserID), agent)+ if err != nil {+ t.Fatal(err)+ }+ if len(overlay.ConnectedApps) != 1 || overlay.ConnectedApps[0].Provider != connectedapps.RemoteProvider ||+ overlay.ConnectedApps[0].ServerName != "mobbin" || overlay.ConnectedApps[0].AccountStatus != "connected" {+ t.Fatalf("connected apps = %+v", overlay.ConnectedApps)+ }+ authorized, err := f.h.ConnectedApps.AuthorizeOverlay(overlay.MCPOverlay, parseUUID(f.taskID))+ if err != nil {+ t.Fatal(err)+ }+ var servers struct {+ MCPServers map[string]struct {+ URL string `json:"url"`+ Headers map[string]string `json:"headers"`+ } `json:"mcpServers"`+ }+ json.Unmarshal(authorized, &servers)+ if servers.MCPServers["mobbin"].URL != remoteTestBase+"/api/apps/mcp/mobbin" ||+ !strings.HasPrefix(servers.MCPServers["mobbin"].Headers["Authorization"], "Bearer ") ||+ servers.MCPServers[connectedapps.GatewayServerName].Headers["Authorization"] == "" {+ t.Fatalf("authorized overlay = %s", authorized)+ }++ token := f.token(t)+ if code, _ := f.remote(t, "", "tools/list", map[string]any{}); code != http.StatusUnauthorized {+ t.Fatalf("remote gateway without token: %d, want 401", code)+ }+ // A read-level agent sees only the read tool.+ if names := f.toolNames(t, token); len(names) != 1 || names[0] != "search_screens" {+ t.Fatalf("read-level tools = %v", names)+ }+ _, result := f.remote(t, token, "tools/call", map[string]any{"name": "search_screens", "arguments": map[string]any{"query": "onboarding"}})+ if !strings.Contains(string(result), `"type":"image"`) {+ t.Fatalf("result must pass through unchanged: %s", result)+ }+ _, blocked := f.remote(t, token, "tools/call", map[string]any{"name": "save_screen", "arguments": map[string]any{}})+ if !strings.Contains(string(blocked), "blocked") {+ t.Fatalf("write at read level = %s", blocked)+ }+ var outcomes []string+ rows, _ := testPool.Query(context.Background(), `SELECT tool_slug || ':' || outcome FROM app_tool_call WHERE task_id = $1 ORDER BY created_at`, f.taskID)+ for rows.Next() {+ var s string+ rows.Scan(&s)+ outcomes = append(outcomes, s)+ }+ rows.Close()+ if strings.Join(outcomes, ",") != "search_screens:ok,save_screen:blocked" {+ t.Fatalf("recorded calls = %v", outcomes)+ }++ if _, text, _ := f.gateway(t, token, "apps_list", nil); !strings.Contains(text, `"server": "mobbin"`) {+ t.Fatalf("apps_list = %s", text)+ }+}++func TestRemoteApps_RefreshExpiryAndReconnect(t *testing.T) {+ f := newRemoteAppsFixture(t)+ f.connect(t, testUserID)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "mobbin", "account_scope": "personal", "level": "write"}})+ token := f.token(t)+ call := func() string {+ _, result := f.remote(t, token, "tools/call", map[string]any{"name": "search_screens", "arguments": map[string]any{}})+ return string(result)+ }++ // Near expiry: refreshed before the call, with the single-use refresh+ // token replaced.+ testPool.Exec(context.Background(), `UPDATE remote_app_connection SET expires_at = now() + interval '30 seconds' WHERE owner_id = $1`, testUserID)+ if res := call(); !strings.Contains(res, "image") {+ t.Fatalf("call after refresh = %s", res)+ }+ if len(f.up.refreshed) != 1 || f.up.refreshed[0] != "refresh-1" || f.up.tokens[len(f.up.tokens)-1] != "access-2" {+ t.Fatalf("refreshed = %v tokens = %v", f.up.refreshed, f.up.tokens)+ }++ // The app rejects a token it should accept: one refresh, then a retry.+ f.up.rejectTokenOf = "access-2"+ if res := call(); !strings.Contains(res, "image") {+ t.Fatalf("call after 401 = %s", res)+ }+ if len(f.up.refreshed) != 2 || f.up.refreshed[1] != "refresh-2" || f.up.tokens[len(f.up.tokens)-1] != "access-3" {+ t.Fatalf("refreshed = %v tokens = %v", f.up.refreshed, f.up.tokens)+ }++ // The refresh token is refused: the account expires and the agent is+ // told to ask for a new connection.+ f.up.refreshErr = &remotemcp.OAuthError{Status: http.StatusBadRequest, Code: "invalid_grant"}+ testPool.Exec(context.Background(), `UPDATE remote_app_connection SET expires_at = now() - interval '1 minute' WHERE owner_id = $1`, testUserID)+ if res := call(); !strings.Contains(res, "apps_request_connection") {+ t.Fatalf("call with refused refresh = %s", res)+ }+ if status := f.personalStatus(t); status != "expired" {+ t.Fatalf("status = %q, want expired", status)+ }+ var leftover []byte+ testPool.QueryRow(context.Background(), `SELECT refresh_token FROM remote_app_connection WHERE owner_id = $1 AND app_slug = 'mobbin'`, testUserID).Scan(&leftover)+ if leftover != nil {+ t.Fatal("an expired account must not keep its refresh token")+ }+ if names := f.toolNames(t, token); len(names) != 0 {+ t.Fatalf("tools of an expired account = %v", names)+ }++ _, text, isErr := f.gateway(t, token, "apps_request_connection", map[string]any{"app": "mobbin", "summary": "Find onboarding patterns"})+ if isErr || !strings.HasPrefix(text, "requested") {+ t.Fatalf("request connection = %s (error %v)", text, isErr)+ }++ // Reconnecting resolves the request and resumes the agent.+ f.up.refreshErr = nil+ f.connect(t, testUserID)+ if status := f.personalStatus(t); status != "active" {+ t.Fatalf("status after reconnect = %q", status)+ }+ if reqs := f.listRequests(t, testUserID); len(reqs) != 1 || reqs[0].Status != "approved" {+ t.Fatalf("connect request after reconnecting = %+v", reqs)+ }+ var note string+ if err := testPool.QueryRow(context.Background(), `+ SELECT handoff_note FROM agent_task_queue+ WHERE agent_id = $1 AND issue_id = $2 AND status = 'queued' AND trigger_evidence_kind = 'app_action_request'+ `, f.agentID, f.issueID).Scan(¬e); err != nil || !strings.Contains(note, "now connected") {+ t.Fatalf("resume run = %q, %v", note, err)+ }+}++func TestRemoteApps_RefreshSurvivesCallerAndDeadClient(t *testing.T) {+ f := newRemoteAppsFixture(t)+ f.connect(t, testUserID)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "mobbin", "account_scope": "personal", "level": "write"}})+ token := f.token(t)+ expireSoon := func() {+ testPool.Exec(context.Background(), `UPDATE remote_app_connection SET expires_at = now() - interval '1 minute' WHERE owner_id = $1`, testUserID)+ }+ search := map[string]any{"name": "search_screens", "arguments": map[string]any{}}++ // A Composio-style guess on multica_apps points at the app's own server.+ for _, tool := range []string{"apps_get_tool", "apps_run_tool"} {+ if _, text, _ := f.gateway(t, token, tool, map[string]any{"tool": "MOBBIN_SEARCH_SCREENS"}); !strings.Contains(text, `MCP server "mobbin"`) {+ t.Fatalf("%s = %s", tool, text)+ }+ }++ // The caller goes away after the app has rotated the single-use refresh+ // token: the new pair is still saved, so the next call needs no refresh.+ expireSoon()+ ctx, cancel := context.WithCancel(context.Background())+ f.up.onRefresh = cancel+ f.remoteCtx(t, ctx, token, "tools/call", search)+ f.up.onRefresh = nil+ if _, res := f.remote(t, token, "tools/call", search); !strings.Contains(string(res), "image") {+ t.Fatalf("call after a cancelled refresh = %s", res)+ }+ if len(f.up.refreshed) != 1 || f.up.tokens[len(f.up.tokens)-1] != "access-2" {+ t.Fatalf("refreshed = %v tokens = %v; the rotated tokens were lost", f.up.refreshed, f.up.tokens)+ }++ // The authorization server forgot the client: the account expires and the+ // client is dropped, so reconnecting registers a new one.+ f.up.refreshErr = &remotemcp.OAuthError{Status: http.StatusUnauthorized, Code: "invalid_client"}+ expireSoon()+ if _, res := f.remote(t, token, "tools/call", search); !strings.Contains(string(res), "apps_request_connection") {+ t.Fatalf("call with a dead client = %s", res)+ }+ var clients int+ testPool.QueryRow(context.Background(), `SELECT count(*) FROM remote_app_oauth_client WHERE redirect_uri = $1`, remoteTestBase+connectedapps.RemoteCallbackPath).Scan(&clients)+ if status := f.personalStatus(t); status != "expired" || clients != 0 {+ t.Fatalf("status = %q, clients = %d; want expired and none", status, clients)+ }+ f.up.refreshErr = nil+ f.connect(t, testUserID)+ if f.up.registered != 2 || f.personalStatus(t) != "active" {+ t.Fatalf("registrations = %d, status = %q", f.up.registered, f.personalStatus(t))+ }+}++func TestRemoteApps_AccountIsolation(t *testing.T) {+ f := newRemoteAppsFixture(t)+ f.connect(t, testUserID)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "mobbin", "account_scope": "personal", "level": "write"}})++ // A run another member triggered never acts as this member's account.+ if _, err := testPool.Exec(context.Background(), `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, f.member, f.taskID); err != nil {+ t.Fatal(err)+ }+ token := f.token(t)+ _, result := f.remote(t, token, "tools/call", map[string]any{"name": "search_screens", "arguments": map[string]any{}})+ if !strings.Contains(string(result), "not connected") || len(f.up.calls) != 0 {+ t.Fatalf("other member's run = %s, upstream calls %v", result, f.up.calls)+ }++ var id string+ testPool.QueryRow(context.Background(), `SELECT id FROM remote_app_connection WHERE owner_id = $1 AND app_slug = 'mobbin'`, testUserID).Scan(&id)+ w := httptest.NewRecorder()+ f.h.DeleteComposioConnection(w, withURLParam(appsReqAs(t, f.member, http.MethodDelete, "/api/integrations/composio/connections/"+id, nil), "id", id))+ if w.Code != http.StatusNotFound || f.personalStatus(t) != "active" {+ t.Fatalf("disconnect by another member: %d, status %s", w.Code, f.personalStatus(t))+ }+ w = httptest.NewRecorder()+ f.h.ConnectTeamApp(w, appsReqAs(t, f.member, http.MethodPost, "/api/apps/team/connect", map[string]string{"toolkit_slug": "mobbin"}))+ if w.Code != http.StatusForbidden {+ t.Fatalf("team connect by a member: %d, want 403", w.Code)+ }++ // A tampered state writes nothing and fails generically.+ before := f.up.issued+ if loc := f.callback(t, "state=forged&code=x"); !strings.Contains(loc, "error=composio_connect_failed") || f.up.issued != before {+ t.Fatalf("forged callback = %q", loc)+ }++ w = httptest.NewRecorder()+ f.h.DeleteComposioConnection(w, withURLParam(appsReqAs(t, testUserID, http.MethodDelete, "/api/integrations/composio/connections/"+id, nil), "id", id))+ if w.Code != http.StatusNoContent || f.personalStatus(t) != "revoked" {+ t.Fatalf("own disconnect: %d, status %s", w.Code, f.personalStatus(t))+ }+ var access []byte+ testPool.QueryRow(context.Background(), `SELECT access_token FROM remote_app_connection WHERE id = $1`, id).Scan(&access)+ if access != nil {+ t.Fatal("a revoked account must not keep its access token")+ }+}++// Without the apps secret key, remote apps are off and nothing changes for+// Composio apps.+func TestRemoteApps_OffWithoutKey(t *testing.T) {+ f := newAppsFixture(t)+ if _, ok := f.h.ConnectedApps.RemoteApp("mobbin"); ok {+ t.Fatal("remote apps must be off without a secret box")+ }+ w := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, "/api/apps/mcp/mobbin", strings.NewReader(`{}`))+ f.h.AppsRemoteGateway(w, withURLParam(req, "app", "mobbin"))+ if w.Code != http.StatusNotFound {+ t.Fatalf("remote gateway without remote apps: %d, want 404", w.Code)+ }+}diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.goindex c6ce988c66..a2e23320cb 100644--- a/server/internal/handler/integrations_composio.go+++ b/server/internal/handler/integrations_composio.go@@ -8,6 +8,7 @@ import ("strings""github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/connectedapps""github.com/multica-ai/multica/server/internal/featureflags"composio "github.com/multica-ai/multica/server/internal/integrations/composio")@@ -229,7 +230,13 @@ func (h *Handler) DeleteComposioConnection(w http.ResponseWriter, r *http.Requesif !ok {return}- if err := h.Composio.Disconnect(r.Context(), userUUID, connUUID); err != nil {+ err := h.Composio.Disconnect(r.Context(), userUUID, connUUID)+ if errors.Is(err, composio.ErrConnectionNotFound) && h.ConnectedApps != nil {+ // Personal remote app accounts are listed with these and removed+ // through the same endpoint.+ _, err = h.ConnectedApps.DisconnectRemote(r.Context(), connUUID, connectedapps.ScopePersonal, userUUID)+ }+ if err != nil {if errors.Is(err, composio.ErrConnectionNotFound) {writeError(w, http.StatusNotFound, "composio connection not found")returndiff --git a/server/internal/handler/team_app_feature.go b/server/internal/handler/team_app_feature.goindex 1d38998aee..28c8f33e6f 100644--- a/server/internal/handler/team_app_feature.go+++ b/server/internal/handler/team_app_feature.go@@ -49,6 +49,23 @@ func (h *Handler) teamAppHasAccount(ctx context.Context, workspaceID pgtype.UUIDreturn true, nil}}+ if h.ConnectedApps == nil {+ return false, nil+ }+ if _, remote := h.ConnectedApps.RemoteApp(slug); !remote {+ return false, nil+ }+ remoteRows, err := h.Queries.ListRemoteAppConnectionsForOwner(ctx, db.ListRemoteAppConnectionsForOwnerParams{+ Scope: connectedapps.ScopeTeam, OwnerID: workspaceID,+ })+ if err != nil {+ return false, err+ }+ for _, row := range remoteRows {+ if row.AppSlug == slug {+ return true, nil+ }+ }return false, nil}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 6a8266b144..6d92aea3d3 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -170,6 +170,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"weixin_login_session": workspaceDelete,"weixin_account_state": workspaceDelete,"workspace_composio_connection": workspaceDelete,+ "remote_app_connection": workspaceDelete, // team rows (owner_id = workspace); personal rows are user-owned+ "remote_app_oauth_client": workspaceDeleteKeep,"agent_app": workspaceDelete,"app_action_rule": workspaceDelete,"app_action_request": workspaceDelete,diff --git a/server/migrations/719_remote_app_connection.down.sql b/server/migrations/719_remote_app_connection.down.sqlnew file mode 100644index 0000000000..cbaf876f8f--- /dev/null+++ b/server/migrations/719_remote_app_connection.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS remote_app_connection;+DROP TABLE IF EXISTS remote_app_oauth_client;diff --git a/server/migrations/719_remote_app_connection.up.sql b/server/migrations/719_remote_app_connection.up.sqlnew file mode 100644index 0000000000..16dec39f64--- /dev/null+++ b/server/migrations/719_remote_app_connection.up.sql@@ -0,0 +1,41 @@+-- Remote MCP apps (MUL-9792): apps whose own MCP server Multica connects to+-- over OAuth instead of through Composio. Multica is the OAuth client; runs+-- reach the app through the connected-apps gateway and never see a token.++-- The OAuth client this deployment registered with an app's authorization+-- server, one per (app, redirect URI). A deployment whose public URL changes+-- registers again instead of reusing a client bound to the old callback.+CREATE TABLE IF NOT EXISTS remote_app_oauth_client (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ app_slug TEXT NOT NULL,+ redirect_uri TEXT NOT NULL,+ authorization_endpoint TEXT NOT NULL,+ token_endpoint TEXT NOT NULL,+ scope TEXT NOT NULL DEFAULT '',+ client_id TEXT NOT NULL,+ -- Sealed with MULTICA_APPS_SECRET_KEY; NULL for a public client.+ client_secret BYTEA,+ token_endpoint_auth_method TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- One account per app and owner. owner_id is the workspace for a team+-- account and the member for a personal one, like the Composio accounts.+-- Tokens are sealed with MULTICA_APPS_SECRET_KEY and cleared on disconnect.+CREATE TABLE IF NOT EXISTS remote_app_connection (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ app_slug TEXT NOT NULL,+ scope TEXT NOT NULL CHECK (scope IN ('team', 'personal')),+ owner_id UUID NOT NULL,+ connected_by UUID NOT NULL,+ oauth_client_id UUID NOT NULL,+ access_token BYTEA,+ refresh_token BYTEA,+ expires_at TIMESTAMPTZ,+ status TEXT NOT NULL DEFAULT 'active'+ CHECK (status IN ('active', 'expired', 'revoked')),+ connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_used_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/720_remote_app_oauth_client_idx.down.sql b/server/migrations/720_remote_app_oauth_client_idx.down.sqlnew file mode 100644index 0000000000..3ef586de62--- /dev/null+++ b/server/migrations/720_remote_app_oauth_client_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_remote_app_oauth_client_app_redirect;diff --git a/server/migrations/720_remote_app_oauth_client_idx.up.sql b/server/migrations/720_remote_app_oauth_client_idx.up.sqlnew file mode 100644index 0000000000..1986323f14--- /dev/null+++ b/server/migrations/720_remote_app_oauth_client_idx.up.sql@@ -0,0 +1,4 @@+-- One registered client per app and callback; concurrent first connects race+-- on this and the loser reads the winner's row.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_remote_app_oauth_client_app_redirect+ ON remote_app_oauth_client (app_slug, redirect_uri);diff --git a/server/migrations/721_remote_app_connection_owner_idx.down.sql b/server/migrations/721_remote_app_connection_owner_idx.down.sqlnew file mode 100644index 0000000000..0bed0febd4--- /dev/null+++ b/server/migrations/721_remote_app_connection_owner_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_remote_app_connection_owner;diff --git a/server/migrations/721_remote_app_connection_owner_idx.up.sql b/server/migrations/721_remote_app_connection_owner_idx.up.sqlnew file mode 100644index 0000000000..9fb63076c0--- /dev/null+++ b/server/migrations/721_remote_app_connection_owner_idx.up.sql@@ -0,0 +1,5 @@+-- One account per owner and app; reconnecting updates the row in place.+-- Owner first so listing an owner's accounts and deleting a workspace's+-- team accounts use it too.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_remote_app_connection_owner+ ON remote_app_connection (scope, owner_id, app_slug);diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex c5af52b107..d12ad16ff7 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1782,6 +1782,36 @@ type QuickAction struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type RemoteAppConnection struct {+ ID pgtype.UUID `json:"id"`+ AppSlug string `json:"app_slug"`+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+ ConnectedBy pgtype.UUID `json:"connected_by"`+ OauthClientID pgtype.UUID `json:"oauth_client_id"`+ AccessToken []byte `json:"access_token"`+ RefreshToken []byte `json:"refresh_token"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ Status string `json:"status"`+ ConnectedAt pgtype.Timestamptz `json:"connected_at"`+ LastUsedAt pgtype.Timestamptz `json:"last_used_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type RemoteAppOauthClient struct {+ ID pgtype.UUID `json:"id"`+ AppSlug string `json:"app_slug"`+ RedirectUri string `json:"redirect_uri"`+ AuthorizationEndpoint string `json:"authorization_endpoint"`+ TokenEndpoint string `json:"token_endpoint"`+ Scope string `json:"scope"`+ ClientID string `json:"client_id"`+ ClientSecret []byte `json:"client_secret"`+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type RuntimeProfile struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/remote_apps.sql.go b/server/pkg/db/generated/remote_apps.sql.gonew file mode 100644index 0000000000..8bb297dc70--- /dev/null+++ b/server/pkg/db/generated/remote_apps.sql.go@@ -0,0 +1,420 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: remote_apps.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const deleteRemoteAppOAuthClient = `-- name: DeleteRemoteAppOAuthClient :exec+DELETE FROM remote_app_oauth_client WHERE id = $1+`++// The authorization server no longer knows the client; the next connect+// registers a new one.+func (q *Queries) DeleteRemoteAppOAuthClient(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteRemoteAppOAuthClient, id)+ return err+}++const getActiveRemoteAppConnection = `-- name: GetActiveRemoteAppConnection :one+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+WHERE app_slug = $1 AND scope = $2 AND owner_id = $3 AND status = 'active'+`++type GetActiveRemoteAppConnectionParams struct {+ AppSlug string `json:"app_slug"`+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++func (q *Queries) GetActiveRemoteAppConnection(ctx context.Context, arg GetActiveRemoteAppConnectionParams) (RemoteAppConnection, error) {+ row := q.db.QueryRow(ctx, getActiveRemoteAppConnection, arg.AppSlug, arg.Scope, arg.OwnerID)+ var i RemoteAppConnection+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.Scope,+ &i.OwnerID,+ &i.ConnectedBy,+ &i.OauthClientID,+ &i.AccessToken,+ &i.RefreshToken,+ &i.ExpiresAt,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getRemoteAppConnection = `-- name: GetRemoteAppConnection :one+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+WHERE id = $1+`++func (q *Queries) GetRemoteAppConnection(ctx context.Context, id pgtype.UUID) (RemoteAppConnection, error) {+ row := q.db.QueryRow(ctx, getRemoteAppConnection, id)+ var i RemoteAppConnection+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.Scope,+ &i.OwnerID,+ &i.ConnectedBy,+ &i.OauthClientID,+ &i.AccessToken,+ &i.RefreshToken,+ &i.ExpiresAt,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getRemoteAppConnectionForOwner = `-- name: GetRemoteAppConnectionForOwner :one+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+WHERE id = $1 AND scope = $2 AND owner_id = $3+`++type GetRemoteAppConnectionForOwnerParams struct {+ ID pgtype.UUID `json:"id"`+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++// Owner-scoped, so an account cannot be changed by guessing its id.+func (q *Queries) GetRemoteAppConnectionForOwner(ctx context.Context, arg GetRemoteAppConnectionForOwnerParams) (RemoteAppConnection, error) {+ row := q.db.QueryRow(ctx, getRemoteAppConnectionForOwner, arg.ID, arg.Scope, arg.OwnerID)+ var i RemoteAppConnection+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.Scope,+ &i.OwnerID,+ &i.ConnectedBy,+ &i.OauthClientID,+ &i.AccessToken,+ &i.RefreshToken,+ &i.ExpiresAt,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getRemoteAppOAuthClient = `-- name: GetRemoteAppOAuthClient :one++SELECT id, app_slug, redirect_uri, authorization_endpoint, token_endpoint, scope, client_id, client_secret, token_endpoint_auth_method, created_at FROM remote_app_oauth_client+WHERE app_slug = $1 AND redirect_uri = $2+`++type GetRemoteAppOAuthClientParams struct {+ AppSlug string `json:"app_slug"`+ RedirectUri string `json:"redirect_uri"`+}++// =====================+// Remote MCP app OAuth clients+// =====================+func (q *Queries) GetRemoteAppOAuthClient(ctx context.Context, arg GetRemoteAppOAuthClientParams) (RemoteAppOauthClient, error) {+ row := q.db.QueryRow(ctx, getRemoteAppOAuthClient, arg.AppSlug, arg.RedirectUri)+ var i RemoteAppOauthClient+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.RedirectUri,+ &i.AuthorizationEndpoint,+ &i.TokenEndpoint,+ &i.Scope,+ &i.ClientID,+ &i.ClientSecret,+ &i.TokenEndpointAuthMethod,+ &i.CreatedAt,+ )+ return i, err+}++const getRemoteAppOAuthClientByID = `-- name: GetRemoteAppOAuthClientByID :one+SELECT id, app_slug, redirect_uri, authorization_endpoint, token_endpoint, scope, client_id, client_secret, token_endpoint_auth_method, created_at FROM remote_app_oauth_client+WHERE id = $1+`++func (q *Queries) GetRemoteAppOAuthClientByID(ctx context.Context, id pgtype.UUID) (RemoteAppOauthClient, error) {+ row := q.db.QueryRow(ctx, getRemoteAppOAuthClientByID, id)+ var i RemoteAppOauthClient+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.RedirectUri,+ &i.AuthorizationEndpoint,+ &i.TokenEndpoint,+ &i.Scope,+ &i.ClientID,+ &i.ClientSecret,+ &i.TokenEndpointAuthMethod,+ &i.CreatedAt,+ )+ return i, err+}++const insertRemoteAppOAuthClient = `-- name: InsertRemoteAppOAuthClient :one+INSERT INTO remote_app_oauth_client (+ app_slug, redirect_uri, authorization_endpoint, token_endpoint, scope,+ client_id, client_secret, token_endpoint_auth_method+) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8+)+ON CONFLICT (app_slug, redirect_uri) DO NOTHING+RETURNING id, app_slug, redirect_uri, authorization_endpoint, token_endpoint, scope, client_id, client_secret, token_endpoint_auth_method, created_at+`++type InsertRemoteAppOAuthClientParams struct {+ AppSlug string `json:"app_slug"`+ RedirectUri string `json:"redirect_uri"`+ AuthorizationEndpoint string `json:"authorization_endpoint"`+ TokenEndpoint string `json:"token_endpoint"`+ Scope string `json:"scope"`+ ClientID string `json:"client_id"`+ ClientSecret []byte `json:"client_secret"`+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`+}++// A concurrent first connect may have registered already; the caller reads+// that row when this returns no rows.+func (q *Queries) InsertRemoteAppOAuthClient(ctx context.Context, arg InsertRemoteAppOAuthClientParams) (RemoteAppOauthClient, error) {+ row := q.db.QueryRow(ctx, insertRemoteAppOAuthClient,+ arg.AppSlug,+ arg.RedirectUri,+ arg.AuthorizationEndpoint,+ arg.TokenEndpoint,+ arg.Scope,+ arg.ClientID,+ arg.ClientSecret,+ arg.TokenEndpointAuthMethod,+ )+ var i RemoteAppOauthClient+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.RedirectUri,+ &i.AuthorizationEndpoint,+ &i.TokenEndpoint,+ &i.Scope,+ &i.ClientID,+ &i.ClientSecret,+ &i.TokenEndpointAuthMethod,+ &i.CreatedAt,+ )+ return i, err+}++const listRemoteAppConnectionsForOwner = `-- name: ListRemoteAppConnectionsForOwner :many+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+WHERE scope = $1 AND owner_id = $2 AND status <> 'revoked'+ORDER BY connected_at DESC+`++type ListRemoteAppConnectionsForOwnerParams struct {+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++// Every account the owner still sees: active and expired, not disconnected.+func (q *Queries) ListRemoteAppConnectionsForOwner(ctx context.Context, arg ListRemoteAppConnectionsForOwnerParams) ([]RemoteAppConnection, error) {+ rows, err := q.db.Query(ctx, listRemoteAppConnectionsForOwner, arg.Scope, arg.OwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []RemoteAppConnection{}+ for rows.Next() {+ var i RemoteAppConnection+ if err := rows.Scan(+ &i.ID,+ &i.AppSlug,+ &i.Scope,+ &i.OwnerID,+ &i.ConnectedBy,+ &i.OauthClientID,+ &i.AccessToken,+ &i.RefreshToken,+ &i.ExpiresAt,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockRemoteAppConnection = `-- name: LockRemoteAppConnection :one+SELECT id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at FROM remote_app_connection+WHERE id = $1+FOR UPDATE+`++// Serializes token refresh: a refresh token is single-use, so two refreshes+// of the same account must not race.+func (q *Queries) LockRemoteAppConnection(ctx context.Context, id pgtype.UUID) (RemoteAppConnection, error) {+ row := q.db.QueryRow(ctx, lockRemoteAppConnection, id)+ var i RemoteAppConnection+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.Scope,+ &i.OwnerID,+ &i.ConnectedBy,+ &i.OauthClientID,+ &i.AccessToken,+ &i.RefreshToken,+ &i.ExpiresAt,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const setRemoteAppConnectionStatus = `-- name: SetRemoteAppConnectionStatus :exec+UPDATE remote_app_connection+SET status = $2,+ access_token = CASE WHEN $2::text = 'active' THEN access_token END,+ refresh_token = CASE WHEN $2::text = 'active' THEN refresh_token END,+ updated_at = now()+WHERE id = $1+`++type SetRemoteAppConnectionStatusParams struct {+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+}++// Leaving active drops the tokens: an expired account needs a new sign-in and+// a revoked one must not keep a usable credential.+func (q *Queries) SetRemoteAppConnectionStatus(ctx context.Context, arg SetRemoteAppConnectionStatusParams) error {+ _, err := q.db.Exec(ctx, setRemoteAppConnectionStatus, arg.ID, arg.Status)+ return err+}++const touchRemoteAppConnection = `-- name: TouchRemoteAppConnection :exec+UPDATE remote_app_connection+SET last_used_at = now()+WHERE id = $1+`++func (q *Queries) TouchRemoteAppConnection(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, touchRemoteAppConnection, id)+ return err+}++const updateRemoteAppConnectionTokens = `-- name: UpdateRemoteAppConnectionTokens :exec+UPDATE remote_app_connection+SET access_token = $2, refresh_token = $3, expires_at = $4, updated_at = now()+WHERE id = $1+`++type UpdateRemoteAppConnectionTokensParams struct {+ ID pgtype.UUID `json:"id"`+ AccessToken []byte `json:"access_token"`+ RefreshToken []byte `json:"refresh_token"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+}++func (q *Queries) UpdateRemoteAppConnectionTokens(ctx context.Context, arg UpdateRemoteAppConnectionTokensParams) error {+ _, err := q.db.Exec(ctx, updateRemoteAppConnectionTokens,+ arg.ID,+ arg.AccessToken,+ arg.RefreshToken,+ arg.ExpiresAt,+ )+ return err+}++const upsertRemoteAppConnection = `-- name: UpsertRemoteAppConnection :one++INSERT INTO remote_app_connection (+ app_slug, scope, owner_id, connected_by, oauth_client_id,+ access_token, refresh_token, expires_at, status+) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8, 'active'+)+ON CONFLICT (scope, owner_id, app_slug) DO UPDATE SET+ connected_by = EXCLUDED.connected_by,+ oauth_client_id = EXCLUDED.oauth_client_id,+ access_token = EXCLUDED.access_token,+ refresh_token = EXCLUDED.refresh_token,+ expires_at = EXCLUDED.expires_at,+ status = 'active',+ connected_at = now(),+ updated_at = now()+RETURNING id, app_slug, scope, owner_id, connected_by, oauth_client_id, access_token, refresh_token, expires_at, status, connected_at, last_used_at, created_at, updated_at+`++type UpsertRemoteAppConnectionParams struct {+ AppSlug string `json:"app_slug"`+ Scope string `json:"scope"`+ OwnerID pgtype.UUID `json:"owner_id"`+ ConnectedBy pgtype.UUID `json:"connected_by"`+ OauthClientID pgtype.UUID `json:"oauth_client_id"`+ AccessToken []byte `json:"access_token"`+ RefreshToken []byte `json:"refresh_token"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+}++// =====================+// Remote MCP app connections+// =====================+func (q *Queries) UpsertRemoteAppConnection(ctx context.Context, arg UpsertRemoteAppConnectionParams) (RemoteAppConnection, error) {+ row := q.db.QueryRow(ctx, upsertRemoteAppConnection,+ arg.AppSlug,+ arg.Scope,+ arg.OwnerID,+ arg.ConnectedBy,+ arg.OauthClientID,+ arg.AccessToken,+ arg.RefreshToken,+ arg.ExpiresAt,+ )+ var i RemoteAppConnection+ err := row.Scan(+ &i.ID,+ &i.AppSlug,+ &i.Scope,+ &i.OwnerID,+ &i.ConnectedBy,+ &i.OauthClientID,+ &i.AccessToken,+ &i.RefreshToken,+ &i.ExpiresAt,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex f09210560a..823bc77edc 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -535,6 +535,9 @@ deleted_weixin_account_states AS (deleted_workspace_composio_connections AS (DELETE FROM workspace_composio_connection WHERE workspace_id = $1),+deleted_team_remote_app_connections AS (+ DELETE FROM remote_app_connection WHERE scope = 'team' AND owner_id = $1+),deleted_agent_apps AS (DELETE FROM agent_app WHERE workspace_id = $1),diff --git a/server/pkg/db/queries/remote_apps.sql b/server/pkg/db/queries/remote_apps.sqlnew file mode 100644index 0000000000..cbb95b2221--- /dev/null+++ b/server/pkg/db/queries/remote_apps.sql@@ -0,0 +1,96 @@+-- =====================+-- Remote MCP app OAuth clients+-- =====================++-- name: GetRemoteAppOAuthClient :one+SELECT * FROM remote_app_oauth_client+WHERE app_slug = $1 AND redirect_uri = $2;++-- name: GetRemoteAppOAuthClientByID :one+SELECT * FROM remote_app_oauth_client+WHERE id = $1;++-- name: InsertRemoteAppOAuthClient :one+-- A concurrent first connect may have registered already; the caller reads+-- that row when this returns no rows.+INSERT INTO remote_app_oauth_client (+ app_slug, redirect_uri, authorization_endpoint, token_endpoint, scope,+ client_id, client_secret, token_endpoint_auth_method+) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8+)+ON CONFLICT (app_slug, redirect_uri) DO NOTHING+RETURNING *;++-- name: DeleteRemoteAppOAuthClient :exec+-- The authorization server no longer knows the client; the next connect+-- registers a new one.+DELETE FROM remote_app_oauth_client WHERE id = $1;++-- =====================+-- Remote MCP app connections+-- =====================++-- name: UpsertRemoteAppConnection :one+INSERT INTO remote_app_connection (+ app_slug, scope, owner_id, connected_by, oauth_client_id,+ access_token, refresh_token, expires_at, status+) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8, 'active'+)+ON CONFLICT (scope, owner_id, app_slug) DO UPDATE SET+ connected_by = EXCLUDED.connected_by,+ oauth_client_id = EXCLUDED.oauth_client_id,+ access_token = EXCLUDED.access_token,+ refresh_token = EXCLUDED.refresh_token,+ expires_at = EXCLUDED.expires_at,+ status = 'active',+ connected_at = now(),+ updated_at = now()+RETURNING *;++-- name: ListRemoteAppConnectionsForOwner :many+-- Every account the owner still sees: active and expired, not disconnected.+SELECT * FROM remote_app_connection+WHERE scope = $1 AND owner_id = $2 AND status <> 'revoked'+ORDER BY connected_at DESC;++-- name: GetActiveRemoteAppConnection :one+SELECT * FROM remote_app_connection+WHERE app_slug = $1 AND scope = $2 AND owner_id = $3 AND status = 'active';++-- name: GetRemoteAppConnectionForOwner :one+-- Owner-scoped, so an account cannot be changed by guessing its id.+SELECT * FROM remote_app_connection+WHERE id = $1 AND scope = $2 AND owner_id = $3;++-- name: GetRemoteAppConnection :one+SELECT * FROM remote_app_connection+WHERE id = $1;++-- name: LockRemoteAppConnection :one+-- Serializes token refresh: a refresh token is single-use, so two refreshes+-- of the same account must not race.+SELECT * FROM remote_app_connection+WHERE id = $1+FOR UPDATE;++-- name: UpdateRemoteAppConnectionTokens :exec+UPDATE remote_app_connection+SET access_token = $2, refresh_token = $3, expires_at = $4, updated_at = now()+WHERE id = $1;++-- name: SetRemoteAppConnectionStatus :exec+-- Leaving active drops the tokens: an expired account needs a new sign-in and+-- a revoked one must not keep a usable credential.+UPDATE remote_app_connection+SET status = $2,+ access_token = CASE WHEN $2::text = 'active' THEN access_token END,+ refresh_token = CASE WHEN $2::text = 'active' THEN refresh_token END,+ updated_at = now()+WHERE id = $1;++-- name: TouchRemoteAppConnection :exec+UPDATE remote_app_connection+SET last_used_at = now()+WHERE id = $1;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 34270cbcb9..2966cbc5df 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -515,6 +515,9 @@ deleted_weixin_account_states AS (deleted_workspace_composio_connections AS (DELETE FROM workspace_composio_connection WHERE workspace_id = $1),+deleted_team_remote_app_connections AS (+ DELETE FROM remote_app_connection WHERE scope = 'team' AND owner_id = $1+),deleted_agent_apps AS (DELETE FROM agent_app WHERE workspace_id = $1),diff --git a/server/pkg/remotemcp/client.go b/server/pkg/remotemcp/client.goindex 95b36f0b9c..471a0ac9b2 100644--- a/server/pkg/remotemcp/client.go+++ b/server/pkg/remotemcp/client.go@@ -165,9 +165,19 @@ func NewSecureHTTPClient(endpoint *url.URL) *http.Client {}}+// StatusError is a non-2xx HTTP answer from a remote MCP endpoint.+type StatusError struct {+ Code int+}++func (e *StatusError) Error() string {+ return fmt.Sprintf("remote MCP returned HTTP %d", e.Code)+}+type rpcResponse struct {JSONRPC string `json:"jsonrpc"`ID json.RawMessage `json:"id"`+ Method string `json:"method,omitempty"`Result json.RawMessage `json:"result"`Error *struct {Code int `json:"code"`@@ -296,7 +306,7 @@ func notify(ctx context.Context, client *http.Client, endpoint *url.URL, headers}defer response.Body.Close()if response.StatusCode < 200 || response.StatusCode >= 300 {- return fmt.Errorf("remote MCP returned HTTP %d", response.StatusCode)+ return &StatusError{Code: response.StatusCode}}written, err := io.Copy(io.Discard, io.LimitReader(response.Body, MaxResponseBytes+1))if err != nil {@@ -333,7 +343,7 @@ func call(ctx context.Context, client *http.Client, endpoint *url.URL, headers h}defer response.Body.Close()if response.StatusCode < 200 || response.StatusCode >= 300 {- return rpcResponse{}, response.Header, fmt.Errorf("remote MCP returned HTTP %d", response.StatusCode)+ return rpcResponse{}, response.Header, &StatusError{Code: response.StatusCode}}raw, err := readResponse(response)if err != nil {@@ -358,9 +368,19 @@ func readResponse(response *http.Response) ([]byte, error) {line := scanner.Text()if strings.HasPrefix(line, "data:") {data := bytes.TrimSpace([]byte(strings.TrimPrefix(line, "data:")))- if len(data) > 0 {- return data, nil+ if len(data) == 0 {+ continue+ }+ // A server may stream progress notifications or its own+ // requests before the response; only a message without a+ // method answers the request.+ var message struct {+ Method string `json:"method"`+ }+ if json.Unmarshal(data, &message) == nil && message.Method != "" {+ continue}+ return data, nil}}if err := scanner.Err(); err != nil {diff --git a/server/pkg/remotemcp/oauth.go b/server/pkg/remotemcp/oauth.goindex 0d2cfafb19..c48a68daa5 100644--- a/server/pkg/remotemcp/oauth.go+++ b/server/pkg/remotemcp/oauth.go@@ -223,6 +223,30 @@ func getOAuthJSON(ctx context.Context, endpoint *url.URL, target any) error {return doOAuthJSON(NewSecureHTTPClient(endpoint), request, target)}+// OAuthError is a non-2xx answer from an OAuth endpoint. Code is the RFC 6749+// error code (invalid_grant, invalid_client, ...) when the body carried one.+type OAuthError struct {+ Status int+ Code string+}++func (e *OAuthError) Error() string {+ if e.Code != "" {+ return fmt.Sprintf("HTTP %d: %s", e.Status, e.Code)+ }+ return fmt.Sprintf("HTTP %d", e.Status)+}++// Rejected reports whether the server refused the grant or client itself, as+// opposed to failing for a reason a retry could fix.+func (e *OAuthError) Rejected() bool {+ switch e.Code {+ case "invalid_grant", "invalid_client", "unauthorized_client":+ return true+ }+ return e.Code == "" && (e.Status == http.StatusBadRequest || e.Status == http.StatusUnauthorized)+}+func doOAuthJSON(client *http.Client, request *http.Request, target any) error {response, err := client.Do(request)if err != nil {@@ -230,8 +254,16 @@ func doOAuthJSON(client *http.Client, request *http.Request, target any) error {}defer response.Body.Close()if response.StatusCode < 200 || response.StatusCode >= 300 {- _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxOAuthResponseBytes))- return fmt.Errorf("HTTP %d", response.StatusCode)+ raw, _ := io.ReadAll(io.LimitReader(response.Body, maxOAuthResponseBytes))+ var body struct {+ Error string `json:"error"`+ }+ _ = json.Unmarshal(raw, &body)+ code := body.Error+ if len(code) > 64 {+ code = code[:64]+ }+ return &OAuthError{Status: response.StatusCode, Code: code}}raw, err := io.ReadAll(io.LimitReader(response.Body, maxOAuthResponseBytes+1))if err != nil {@@ -281,12 +313,24 @@ func RegisterOAuthClient(ctx context.Context, metadata OAuthMetadata, redirectURif strings.TrimSpace(response.ClientID) == "" {return OAuthClientRegistration{}, errors.New("dynamic client registration returned no client id")}- if response.TokenEndpointAuthMethod == "" {- response.TokenEndpointAuthMethod = "none"- }+ response.TokenEndpointAuthMethod = registeredAuthMethod(response.TokenEndpointAuthMethod, response.ClientSecret)return OAuthClientRegistration(response), nil}+// registeredAuthMethod fills in a method the registration response omitted.+// RFC 7591 §2 defaults it to client_secret_basic, which only applies when the+// server actually issued a secret.+func registeredAuthMethod(method, secret string) string {+ switch {+ case method != "":+ return method+ case secret != "":+ return "client_secret_basic"+ default:+ return "none"+ }+}+func BuildAuthorizationURL(metadata OAuthMetadata, registration OAuthClientRegistration, redirectURI, state, verifier, scope string) (string, error) {endpoint, err := url.Parse(metadata.AuthorizationEndpoint)if err != nil {diff --git a/server/pkg/remotemcp/session.go b/server/pkg/remotemcp/session.gonew file mode 100644index 0000000000..b607366463--- /dev/null+++ b/server/pkg/remotemcp/session.go@@ -0,0 +1,111 @@+package remotemcp++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/url"+)++// maxToolPages bounds tools/list pagination against a server that never stops+// returning a cursor.+const maxToolPages = 20++// Session is an initialized MCP session with one remote endpoint. Results are+// returned as the server sent them, so content such as images reaches the+// caller unchanged.+type Session struct {+ client *http.Client+ endpoint *url.URL+ headers http.Header+ sessionID string+ nextID int+}++// OpenSession validates the endpoint, then runs the MCP initialize handshake.+func OpenSession(ctx context.Context, rawEndpoint string, headers http.Header) (*Session, error) {+ endpoint, err := ValidatePublicHTTPSEndpoint(ctx, rawEndpoint, nil, nil)+ if err != nil {+ return nil, err+ }+ s := &Session{client: NewSecureHTTPClient(endpoint), endpoint: endpoint, headers: headers}+ versions := SupportedProtocolVersions()+ result, responseHeaders, err := s.request(ctx, "initialize", map[string]any{+ "protocolVersion": versions[0],+ "capabilities": map[string]any{},+ "clientInfo": map[string]any{"name": "multica", "version": "1"},+ })+ if err != nil {+ return nil, fmt.Errorf("initialize remote MCP: %w", err)+ }+ s.sessionID = responseHeaders.Get("Mcp-Session-Id")+ var initialized struct {+ ProtocolVersion string `json:"protocolVersion"`+ }+ if err := json.Unmarshal(result, &initialized); err != nil || !containsString(versions, initialized.ProtocolVersion) {+ return nil, fmt.Errorf("remote MCP negotiated unsupported protocol version %q", initialized.ProtocolVersion)+ }+ if err := notify(ctx, s.client, s.endpoint, s.headers, s.sessionID, map[string]any{+ "jsonrpc": "2.0", "method": "notifications/initialized", "params": map[string]any{},+ }); err != nil {+ return nil, fmt.Errorf("confirm remote MCP initialization: %w", err)+ }+ return s, nil+}++func (s *Session) request(ctx context.Context, method string, params any) (json.RawMessage, http.Header, error) {+ s.nextID+++ response, headers, err := call(ctx, s.client, s.endpoint, s.headers, s.sessionID, map[string]any{+ "jsonrpc": "2.0", "id": s.nextID, "method": method, "params": params,+ })+ if err != nil {+ return nil, headers, err+ }+ return response.Result, headers, nil+}++// ListTools returns every tool object the server lists, following cursors.+func (s *Session) ListTools(ctx context.Context) ([]json.RawMessage, error) {+ var tools []json.RawMessage+ cursor := ""+ for page := 0; page < maxToolPages; page++ {+ params := map[string]any{}+ if cursor != "" {+ params["cursor"] = cursor+ }+ raw, _, err := s.request(ctx, "tools/list", params)+ if err != nil {+ return nil, fmt.Errorf("list remote MCP tools: %w", err)+ }+ var result struct {+ Tools []json.RawMessage `json:"tools"`+ NextCursor string `json:"nextCursor"`+ }+ if err := json.Unmarshal(raw, &result); err != nil {+ return nil, fmt.Errorf("decode tools/list result: %w", err)+ }+ tools = append(tools, result.Tools...)+ if result.NextCursor == "" {+ return tools, nil+ }+ cursor = result.NextCursor+ }+ return nil, errors.New("remote MCP tools/list did not finish paging")+}++// CallTool runs one tool and returns the raw tools/call result.+func (s *Session) CallTool(ctx context.Context, name string, args map[string]any) (json.RawMessage, error) {+ if args == nil {+ args = map[string]any{}+ }+ raw, _, err := s.request(ctx, "tools/call", map[string]any{"name": name, "arguments": args})+ if err != nil {+ return nil, err+ }+ if len(raw) == 0 {+ return nil, errors.New("remote MCP tools/call returned no result")+ }+ return raw, nil+}diff --git a/server/pkg/remotemcp/session_test.go b/server/pkg/remotemcp/session_test.gonew file mode 100644index 0000000000..ed450c82d9--- /dev/null+++ b/server/pkg/remotemcp/session_test.go@@ -0,0 +1,119 @@+package remotemcp++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestSessionListsPagesAndCallsThroughSSE(t *testing.T) {+ var sawSession, sawAuth bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer tok" {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ sawAuth = true+ var req struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params"`+ }+ body, _ := io.ReadAll(r.Body)+ _ = json.Unmarshal(body, &req)+ if req.Method != "initialize" && r.Header.Get("Mcp-Session-Id") == "s-1" {+ sawSession = true+ }+ switch req.Method {+ case "initialize":+ w.Header().Set("Mcp-Session-Id", "s-1")+ fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":"2025-03-26"}}`, req.ID)+ case "notifications/initialized":+ w.WriteHeader(http.StatusAccepted)+ case "tools/list":+ if strings.Contains(string(req.Params), `"cursor":"p2"`) {+ fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"b"}]}}`, req.ID)+ return+ }+ fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"a","annotations":{"readOnlyHint":true}}],"nextCursor":"p2"}}`, req.ID)+ case "tools/call":+ w.Header().Set("Content-Type", "text/event-stream")+ fmt.Fprint(w, "event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\",\"params\":{}}\n\n")+ fmt.Fprintf(w, "event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":[{\"type\":\"image\",\"data\":\"AAA\",\"mimeType\":\"image/png\"}]}}\n\n", req.ID)+ }+ }))+ defer server.Close()+ t.Setenv(DevOriginsEnv, server.URL)++ headers := http.Header{"Authorization": {"Bearer tok"}}+ session, err := OpenSession(t.Context(), server.URL, headers)+ if err != nil {+ t.Fatal(err)+ }+ tools, err := session.ListTools(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ if len(tools) != 2 || !strings.Contains(string(tools[0]), "readOnlyHint") {+ t.Fatalf("tools = %s", tools)+ }+ result, err := session.CallTool(t.Context(), "a", nil)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(result), `"type":"image"`) {+ t.Fatalf("result = %s", result)+ }+ if !sawAuth || !sawSession {+ t.Fatalf("auth=%v session=%v", sawAuth, sawSession)+ }+}++func TestSessionReportsUnauthorizedStatus(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer server.Close()+ t.Setenv(DevOriginsEnv, server.URL)++ _, err := OpenSession(t.Context(), server.URL, nil)+ var status *StatusError+ if !errors.As(err, &status) || status.Code != http.StatusUnauthorized {+ t.Fatalf("err = %v, want StatusError 401", err)+ }+}++func TestOAuthErrorCarriesCode(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = io.WriteString(w, `{"error":"invalid_grant","error_description":"refresh token already used"}`)+ }))+ defer server.Close()++ request, _ := http.NewRequest(http.MethodPost, server.URL, nil)+ err := doOAuthJSON(server.Client(), request, &struct{}{})+ var oauthErr *OAuthError+ if !errors.As(err, &oauthErr) || oauthErr.Code != "invalid_grant" || !oauthErr.Rejected() {+ t.Fatalf("err = %#v", err)+ }+ if transient := (&OAuthError{Status: http.StatusServiceUnavailable}); transient.Rejected() {+ t.Fatal("a 503 must not count as a rejected grant")+ }+}++func TestRegisteredAuthMethodDefaultsPerRFC7591(t *testing.T) {+ for _, tc := range []struct{ method, secret, want string }{+ {"", "", "none"},+ {"", "s", "client_secret_basic"},+ {"client_secret_post", "s", "client_secret_post"},+ } {+ if got := registeredAuthMethod(tc.method, tc.secret); got != tc.want {+ t.Fatalf("registeredAuthMethod(%q, %q) = %q, want %q", tc.method, tc.secret, got, tc.want)+ }+ }+}