Files
PaperClipAI/server/src/services/dot-invitations.ts
T
DottaandClaude Opus 5.5 904c01d1a3 feat(mcp): graduate Assistant connections (MCP) out of experimental (#22015)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Assistant connections (MCP) let an outside assistant, or another
Paperclip instance, sign in as a person and use the `/mcp/paperclip`
endpoint
> - The feature was behind the experimental `enablePublicMcp` setting.
The setting was off by default and in practice off on Cloud stacks
> - Instance-to-instance work (one person's agent files a task on a
colleague's instance) fails when the receiving instance has the setting
off
> - This pull request moves the feature out of Experimental. It is now
always on, and a stored or Cloud-managed "off" value is ignored
> - The benefit is that every authenticated instance with a public URL,
including Cloud workspaces, accepts assistant connections with no setup
step

## Linked Issues or Issue Description

**Subsystem affected**
Public MCP (`server/src/services/public-mcp/`), instance settings,
Connectors → Assistant Connection (MCP) setup page, Experimental
settings page.

**Problem or motivation**
A remote MCP connector on one instance cannot use another instance's
`/mcp/paperclip` unless an admin on the other instance finds and turns
on an experimental toggle. On Cloud, the toggle is off and is managed by
the fleet. Instance-to-instance delegation therefore does not work by
default.

**Proposed solution**
Remove the gate. Keep `enablePublicMcp` only as a compatibility key, the
same way `enableApps` was graduated: old stored rows, PATCH bodies and
Cloud managed configs still parse, but the effective value is always
`true`.

**Alternatives considered**
An instance-admin kill switch that defaults ON. I did not keep one. Each
person already controls access: a connection exists only after that
person approves OAuth consent for one company, and the person or an
admin can revoke it. Deployment policy (authenticated mode and a valid
public URL) still decides whether the endpoint exists. A second switch
would add a state that can silently break instance-to-instance work
again. A schema migration was also not needed: the value lives in the
`experimental` JSON column, and the stored key becomes inert.

**Roadmap alignment**
Requested by the maintainer to enable instance-to-instance
communication.

## What Changed

- `packages/shared`: `enablePublicMcp` is a deprecated compatibility
key. The schema default is `true`. The feature catalog entry is
"Assistant connections (compatibility)" with both defaults `true`.
- `server` instance settings: normalization always returns
`enablePublicMcp: true`. The Cloud managed overlay skips the key, so a
fleet value of `false` cannot disable it. Removed the key from the Cloud
staging experimental-key list. Removed the client-mirror policy step
that ran only when the toggle changed.
- `server` public MCP: personal discovery, OAuth, tools, setup and event
delivery no longer read instance settings (`isEnabled()` returns `true`
for the personal endpoint without a DB read). Dot, Grok and Muse agent
connections keep their own experimental settings.
- `server` Cloud paths: the client-mirror sync, the hosted event
authority, the ingress-handoff expiry worker and the idle sleep proof
treat the front door as enabled. The warm-standby `503
workspace_unclaimed` behavior is unchanged.
- `server` Dot/Grok gates: they no longer also require
`enablePublicMcp`. Error messages no longer tell people to enable
Assistant connections.
- `ui`: removed the Experimental toggle, the "Enable assistant
connections / Open Experimental settings" block on the Assistant
Connection page, and the "Enable Assistant connections (MCP)" hint in
Dot setup. Updated the Dot and Grok copy.
- Storybook: deleted the Experimental-setting story and removed the
"enable the experiment" step from the journey and presenter.
- Docs: `doc/public-mcp.md` ("Enable an instance", "Start from
Connections", `GET /api/mcp/setup`), `doc/openai-dot-runner.md`,
`doc/idle-grok-dispatch.md`, and the agent-access map.
- Tests: new red/green tests for "enabled with no setting stored" and "a
stored or managed off value is ignored". Removed the tests for the
"disabled" behavior, which no longer exists.

## Verification

- Red/green: with the old source and the new tests,
`instance-settings-readonly.test.ts`,
`instance-settings-service.test.ts` and `public-mcp.test.ts` fail (4
failures, and the public-MCP suite fails in `beforeAll` because
`isEnabled()` was `false` with no setting stored). With the new source
they pass.
- `server`: `public-mcp.test.ts`, instance-settings (readonly, service,
managed overlay), `managed-config`, `cloud-event-authority`,
`events-work`, `dot-runner`, `dot-oauth-onboarding` and
`agent-runtime-assignments`. 354 passed.
- Cloud client-mirror lifecycle
(`client-mirror-lifecycle.postgres.test.ts`, skipped in CI) passed
against a local Postgres 17 with
`PAPERCLIP_MCP_SLEEP_TEST_DATABASE_URL`. 6/6, plus `events-work` 28/28.
- Idle and sleep: `idle-incoming-wake` (service and route),
`idle-deadline-proof`, `idle-incoming-wake-capability`,
`idle-sleep-proof`, `client-mirror-ack`, `recovery-deadline-acceptance`
and `idle-completed-history` pass. The warm-standby test now also
asserts that discovery after the claim does no SQL read.
- `ui`: `InstanceExperimentalSettings`, `AssistantConnection`,
`NewAgentDialog`, `NewAgent` and `ExternalAgentInviteDialog.muse` pass.
267 passed.
- Typecheck: `packages/shared`, `server` and `ui` pass. `node
scripts/check-maps.mjs` passes.
- `pnpm verify`: see the CI checks on this PR.
- After the deploy: confirm
`/.well-known/oauth-protected-resource/mcp/paperclip` and `/mcp/setup`
return 200 on paperclip.staging without changing any setting.

## Risks

- Behavior change: instances that had the setting off now serve
discovery, OAuth and `/mcp/paperclip`. Security invariants are
unchanged: the endpoint is still mounted only in authenticated mode with
a valid public URL, OAuth still needs a real signed-in user's consent,
local implicit board authority cannot approve, and revocation works the
same way.
- Cloud sleep: on a managed stack, the MCP sleep proof blocks sleep
until the client mirror publishes the tenant front door to Cloud. The
client-mirror sync runs at boot and does this once. Stacks that already
had the flag on use this path today. A stack whose Cloud connector
cannot publish the mirror would stay awake. Watch fleet sleep after the
deploy.
- Personal public-MCP requests now read instance settings one time less.
- Fleet admin: the Cloud fleet catalog can still show and set
`enablePublicMcp`. The value is ignored. Removing it from the fleet
catalog is a separate change in the Cloud repo.
- No migration. The `0354` trigger still compares the stored key. That
causes at most one extra connector-runtime invalidation if an old client
writes the key.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:42:36 -06:00

96 lines
7.6 KiB
TypeScript

import { and, desc, eq, isNull, ne, sql } from "drizzle-orm";
import { activityLog, agents, companies, dotAgentBindings, type Db } from "@paperclipai/db";
import { agentService } from "./agents.js";
import { createAgentLifecycle, scheduleAgentLifecycle } from "./agent-lifecycle.js";
import { withDedicatedDbConnection } from "@paperclipai/db";
import { approvalService } from "./approvals.js";
import { accessService } from "./access.js";
import { agentInstructionsService } from "./agent-instructions.js";
import { loadDefaultAgentInstructionsBundle } from "./default-agent-instructions.js";
import { logActivity } from "./activity-log.js";
import { dotRunnerBroker } from "./dot-runner-broker.js";
import { notFound, unprocessable } from "../errors.js";
/** One unfinished invitation per operator/company. Only non-secret references are persisted. */
export function dotInvitationService(db: Db, provider: "openai_dot" | "grok_bot" = "openai_dot") {
const invitationKey = provider === "grok_bot" ? "grokInvitation" : "dotInvitation";
const source = provider === "grok_bot" ? "grok-invitation" : "dot-invitation";
const providerName = provider === "grok_bot" ? "Grok Bot" : "Dot";
async function pending(database: Db, companyId: string, operatorId: string, recoverIncomplete = false) {
const rows = await database.select({ agent: agents, binding: dotAgentBindings })
.from(agents).leftJoin(dotAgentBindings, and(eq(dotAgentBindings.agentId, agents.id), isNull(dotAgentBindings.revokedAt)))
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"),
eq(agents.adapterType, "paperclip_runner"), sql`${agents.adapterConfig}->>'provider' = ${provider}`,
sql`((${recoverIncomplete} and ${agents.metadata}->${invitationKey}->>'operatorId' = ${operatorId}
and ${agents.lifecycleOperation}->>'responsibleUserId' = ${operatorId}) or exists (select 1 from ${activityLog} where ${activityLog.companyId} = ${agents.companyId}
and ${activityLog.entityId} = ${agents.id}::text and ${activityLog.entityType} = 'agent'
and ${activityLog.actorType} = 'user' and ${activityLog.actorId} = ${operatorId}
and ${activityLog.action} = 'agent.hire_created' and ${activityLog.details}->>'source' = ${source}))`)).orderBy(desc(agents.createdAt));
return rows.find(row => row.binding?.status !== "ready" || row.agent.lifecycleState !== "ready")?.agent ?? null;
}
async function describe(agent: Pick<typeof agents.$inferSelect, "id" | "name" | "companyId" | "status" | "role" | "reportsTo" | "metadata">, database: Db = db) {
const approval = await approvalService(database).findOpenHireApprovalForAgent(agent.companyId, agent.id);
return { agent: { id: agent.id, name: agent.name, status: agent.status, ...(provider === "grok_bot" ? { role: agent.role, reportsTo: agent.reportsTo, botName: (agent.metadata?.[invitationKey] as { botName?: string } | undefined)?.botName ?? agent.name } : {}) }, approvalId: approval?.id ?? null,
binding: await dotRunnerBroker(database).bindingForAgent(agent.companyId, agent.id) };
}
return {
async resume(companyId: string, operatorId: string) {
const agent = await pending(db, companyId, operatorId);
return agent ? describe(agent) : null;
},
async create(companyId: string, operatorId: string, details?: { name?: string; botName?: string; role?: typeof agents.$inferSelect.role; reportsTo?: string | null }) {
if (!await dotRunnerBroker(db).enabled(provider)) throw unprocessable(`Enable ${providerName} in experimental settings.`);
const database = db;
const lockKey = `paperclip:${source}:${companyId}:${operatorId}`;
return withDedicatedDbConnection(db, lockDb => lockDb.transaction(async lock => {
await lock.execute(sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`);
// SQL locking also serializes retries on different control-plane replicas.
const [company] = await database.select().from(companies).where(eq(companies.id, companyId));
if (!company) throw notFound("Company not found");
if (company.status !== "active") throw unprocessable(`Activate this company before inviting ${providerName}.`);
const existing = await pending(database, companyId, operatorId, true);
if (existing) {
const [completed] = await database.select({ id: activityLog.id }).from(activityLog).where(and(
eq(activityLog.companyId, companyId), eq(activityLog.entityId, existing.id),
eq(activityLog.action, "agent.hire_created"), eq(activityLog.actorId, operatorId),
sql`${activityLog.details}->>'source' = ${source}`)).limit(1);
if (completed) return describe(existing, database);
}
const svc = agentService(database);
let created = existing ?? await createAgentLifecycle(database).requestHire(companyId, {
name: details?.name?.trim() || providerName, role: details?.role ?? "general", reportsTo: details?.reportsTo, adapterType: "paperclip_runner",
adapterConfig: { provider, lifecycleMode: "per_turn", allowUnmeteredProvider: true,
dotWorkspaceAccess: false, dotAttachmentAccess: false },
runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } },
status: company.requireBoardApprovalForNewAgents ? "pending_approval" : "idle",
metadata: { [invitationKey]: { operatorId, ...(provider === "grok_bot" ? { botName: details?.botName ?? details?.name ?? providerName } : {}) } },
}, { createdByUserId: operatorId });
const bundle = await agentInstructionsService(database).materializeManagedBundle(created,
await loadDefaultAgentInstructionsBundle("default"), { entryFile: "AGENTS.md", replaceExisting: false });
created = (await svc.update(created.id, { adapterConfig: bundle.adapterConfig }, { allowPendingApprovalConfigUpdate: true }))!;
await database.transaction(async tx => {
const txDb = tx as unknown as Db;
const access = accessService(txDb);
await access.ensureMembership(companyId, "agent", created.id, "member", "active");
await access.setPrincipalPermission(companyId, "agent", created.id, "tasks:assign", true, operatorId);
const approval = await approvalService(txDb).findOpenHireApprovalForAgent(companyId, created.id) ?? (company.requireBoardApprovalForNewAgents ? await approvalService(txDb).create(companyId, {
type: "hire_agent", status: "pending", requestedByUserId: operatorId,
payload: { agentId: created.id, name: created.name, role: created.role, adapterType: created.adapterType,
adapterConfig: created.adapterConfig, runtimeConfig: created.runtimeConfig, metadata: created.metadata,
budgetMonthlyCents: created.budgetMonthlyCents, requestedConfigurationSnapshot: {
adapterType: created.adapterType, runtimeConfig: created.runtimeConfig, adapterConfig: created.adapterConfig,
} },
}) : null);
await logActivity(txDb, { companyId, actorType: "user", actorId: operatorId, action: "agent.hire_created",
entityType: "agent", entityId: created.id, details: { name: created.name, role: created.role,
requiresApproval: !!approval, approvalId: approval?.id ?? null, source } });
if (approval) await logActivity(txDb, { companyId, actorType: "user", actorId: operatorId, action: "approval.created",
entityType: "approval", entityId: approval.id, details: { type: "hire_agent", agentId: created.id } });
});
scheduleAgentLifecycle(db, created.id);
return describe(created, database);
}));
},
};
}