mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix(tool-access): keep a personal OAuth URL draft that needs its user's sign-in (#20167)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents and people can connect a custom remote MCP server ("Connect
your own MCP server") through `POST
/api/companies/{companyId}/tools/apps/connect`
> - A draft that declares OAuth for one user (`authMode: "oauth"`,
`grantKind: "user"`) has no user grant until the OAuth callback
> - Its first health check stops at `user_authorization_required` before
any request reaches the server
> - The connect flow handles only `oauth_challenge` as "needs sign-in",
so it deletes the draft and returns a 422 with a `setupUrl` to the
deleted row
> - The person who opens that link finds a connection that does not
exist
> - This pull request keeps the draft and starts sign-in, and it removes
links to a deleted draft from the error
> - The benefit is that an agent can start a per-user OAuth connection
for its user, and the link it gets back opens a draft the user can sign
in to
## Linked Issues or Issue Description
**What happened?**
An agent called `POST /api/companies/{companyId}/tools/apps/connect` for
a per-user OAuth remote MCP server. The call returned 422
`user_authorization_required`. The body held a `draft` connection id and
a `setupUrl` / `reconnectUrl` of `/apps/<id>/permissions`. A later `GET
/api/tool-connections/<id>` returned 404, and the connection was not in
the company's connection list. The connect flow had deleted the draft
after it built the error.
Also: for a custom server draft with no `sourceTemplateKey`, the agent
sign-in hand-off from `start-authorization` is
`/<prefix>/apps/connect?resume=<id>` with no `source`. The connect route
sends a link without `source` to the Apps list, so the user does not see
the sign-in.
**Expected behavior**
The draft stays, sign-in starts, and the returned link opens a page
where the user can click **Connect as me**. If setup deletes its draft,
the error carries no link to that draft and says what to do next.
**Steps to reproduce**
1. As an agent with a responsible user, call `POST
/api/companies/{companyId}/tools/apps/connect` for a custom remote MCP
URL with `authMode: "oauth"` and `grantKind: "user"`.
2. See the 422 `user_authorization_required` with a `setupUrl`.
3. Call `GET /api/tool-connections/<connectionId>`. It returns 404.
**Paperclip version or commit**
Rebased onto `master` at `2d06567795`.
## What Changed
- `server/src/services/tool-access.ts`: on a fresh personal OAuth draft,
treat `user_authorization_required` from the first health check like
`oauth_challenge`. Keep the draft and start sign-in.
- `server/src/services/tool-access.ts`: when setup deletes its draft,
remove `setupUrl` / `reconnectUrl` for that draft from the 422. Add
`connectionRemoved: true` and a `nextStep` message.
- `server/src/services/tool-access/oauth/authorization-start.ts`: for a
draft with no app source, send the agent's hand-off to
`/<prefix>/apps/<id>/permissions`, not to `/apps/connect?resume=<id>`.
- `server/src/__tests__/generic-mcp-connection.test.ts`: 3 regression
tests covering draft preservation, stripped dead links on removed
drafts, and agent custom-server hand-off URLs.
-
`server/src/__tests__/connection-management-delegated-policy.integration.test.ts`:
update the custom-server hand-off assertion to expect
`/<prefix>/apps/<id>/permissions` (while asserting curated
`google-workspace` apps still hand off to
`/apps/connect?resume=<id>&source=google-workspace`), and add a
full-stack HTTP E2E integration test verifying an agent-started personal
OAuth draft stays alive (`200` on GET, `firstSignInPending: true`,
`canConnectAsCurrentUser: true`) until the addressed user signs in
through `start-authorization` and `/api/tools/oauth/callback`.
## Verification
- Red-before-fix on `master` (`2d06567795`): all 3 new regression tests
in `generic-mcp-connection.test.ts` fail (`422
user_authorization_required` instead of `201`, missing
`connectionRemoved: true` with dead `setupUrl`/`reconnectUrl` still
present).
- Green-after-fix locally:
- `pnpm --filter @paperclipai/server typecheck`: passed (0 errors)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/generic-mcp-connection.test.ts
src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts`:
121/121 passed
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/connection-management-delegated-policy.integration.test.ts
src/__tests__/tool-access-oauth-protocol.integration.test.ts`: 41/41
passed (including full-stack HTTP agent-to-human E2E sign-in test)
- `pnpm verify --base 2d06567795 --explain` selects 1947/2301 Vitest
files because `server/src/services/tool-access.ts` is broadly imported;
focused suites and typecheck passed locally and required CI supplies
broad sharded coverage.
## Risks
- Low risk. The new path applies only to a draft created in the same
connect call, with `authMode: "oauth"` and `grantKind: "user"`. Other
health-check errors still delete the draft as before.
- The 422 body for a deleted draft no longer has `setupUrl` /
`reconnectUrl`. A client that read those fields got a link to a deleted
row, so no working flow depends on them.
- Compatible with #22714 (`firstSignInPending`): an awaiting personal
draft is marked `firstSignInPending: true` in the Apps list while
remaining reachable via `GET /api/tool-connections/:id` and
`start-authorization` until the user signs in, after which
`firstSignInPending` clears and the connection becomes `active`.
- Not in scope: after a user signs in on a personal draft with no
installs, the defaults give access to all agents. That is a
sharing-default design question, not part of this fix.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and
code execution (original PR commit).
- Rebase, delegated-policy test alignment, full-stack E2E integration
test, and local verification: Antigravity agent with shell, edit, and
test tools.
## 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
- [ ] I have updated relevant documentation to reflect my changes (no
docs change needed)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
This commit is contained in:
4 files changed
+292
-8
No files matched your search
@@ -2993,13 +2993,25 @@ export function toolAccessService(
|
||||
allowUnauthenticatedProbe: unauthenticatedPersonalProbe,
|
||||
});
|
||||
} catch (error) {
|
||||
const healthFailureCode =
|
||||
error instanceof HttpError ? asRecord(error.details).code : null;
|
||||
// A new personal OAuth draft has no user grant until the callback, so
|
||||
// its probe stops at "needs the current user's authorization" before
|
||||
// any request reaches the server. That is the same sign-in-required
|
||||
// state as a 401 challenge, not a failed setup: keep the draft and
|
||||
// start sign-in instead of deleting it and returning its dead link.
|
||||
const personalOAuthDraftNeedsSignIn =
|
||||
healthFailureCode === "user_authorization_required" &&
|
||||
genericAuthKind === "oauth" &&
|
||||
Boolean(personalIdentityUserId) &&
|
||||
!retainedPersonalIdentity?.grant;
|
||||
if (
|
||||
(!galleryEntry || remoteMcpConnector) &&
|
||||
input.authMode !== "none" &&
|
||||
input.authMode !== "bearer" &&
|
||||
input.authMode !== "custom_headers" &&
|
||||
error instanceof HttpError &&
|
||||
asRecord(error.details).code === "oauth_challenge"
|
||||
(healthFailureCode === "oauth_challenge" || personalOAuthDraftNeedsSignIn)
|
||||
) {
|
||||
const [oauthConnection] = await db
|
||||
.select()
|
||||
@@ -3125,6 +3137,7 @@ export function toolAccessService(
|
||||
} catch (error) {
|
||||
if (personalPublicSetupEstablished) throw error;
|
||||
let identityRollbackError: unknown = null;
|
||||
let removedConnectionId: string | null = null;
|
||||
let preserveConcurrentRevival = false;
|
||||
if (connectionRow && revivedConnectionPrevious) {
|
||||
const attemptedConnection = connectionRow;
|
||||
@@ -3256,10 +3269,11 @@ export function toolAccessService(
|
||||
}
|
||||
} else if (connectionRow) {
|
||||
const failedConnectionId = connectionRow.id;
|
||||
await writeToolConnectionHealthChange(db, { companyId, id: failedConnectionId }, tx => tx
|
||||
const removed = await writeToolConnectionHealthChange(db, { companyId, id: failedConnectionId }, tx => tx
|
||||
.delete(toolConnections)
|
||||
.where(eq(toolConnections.id, failedConnectionId)))
|
||||
.catch(() => undefined);
|
||||
.then(() => true, () => false);
|
||||
if (removed) removedConnectionId = failedConnectionId;
|
||||
}
|
||||
if (
|
||||
!preserveConcurrentRevival &&
|
||||
@@ -3303,10 +3317,30 @@ export function toolAccessService(
|
||||
},
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
throw withoutRemovedConnectionLinks(error, removedConnectionId);
|
||||
}
|
||||
}
|
||||
|
||||
// A setup failure deletes its new draft, so a credential error raised while
|
||||
// probing it must not hand the caller a link to that draft: the link would
|
||||
// open a connection that no longer exists. Edit the error in place so its
|
||||
// remote-failure classification, keyed by identity, still applies.
|
||||
function withoutRemovedConnectionLinks(error: unknown, removedConnectionId: string | null): unknown {
|
||||
if (!removedConnectionId || !(error instanceof HttpError)) return error;
|
||||
const details = asRecord(error.details);
|
||||
const removedPath = `/apps/${removedConnectionId}/permissions`;
|
||||
if (details.setupUrl !== removedPath && details.reconnectUrl !== removedPath) return error;
|
||||
const rest = { ...details };
|
||||
delete rest.setupUrl;
|
||||
delete rest.reconnectUrl;
|
||||
error.details = {
|
||||
...rest,
|
||||
connectionRemoved: true,
|
||||
nextStep: "This setup was not saved. Start the connection again; do not send a link to this setup.",
|
||||
};
|
||||
return error;
|
||||
}
|
||||
|
||||
async function assertCatalogEntriesForConnection(
|
||||
companyId: string,
|
||||
connectionId: string,
|
||||
|
||||
@@ -234,9 +234,18 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
|
||||
if (!company) throw notFound("Company not found");
|
||||
// A relative app route: the agent links it in chat, where it opens on
|
||||
// whichever host the person uses, never the server's own listen address.
|
||||
const destination = `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}?${new URLSearchParams({
|
||||
[connection.status === "draft" ? "resume" : "reconnect"]: connection.id,
|
||||
...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) })}`;
|
||||
// The connect wizard only opens for a known app source. A custom server
|
||||
// has none, so send its user to the connection's own page, where they
|
||||
// sign in as themselves.
|
||||
const customServer = !sourceTemplateKey && connection.credentialSource !== "vercel_connect";
|
||||
const query = new URLSearchParams(customServer
|
||||
? { ...(intentLink ? { intent: intentLink.id } : {}) }
|
||||
: { [connection.status === "draft" ? "resume" : "reconnect"]: connection.id,
|
||||
...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) }).toString();
|
||||
const destination = (customServer
|
||||
? `/${encodeURIComponent(company.prefix)}/apps/${encodeURIComponent(connection.id)}/permissions`
|
||||
: `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}`)
|
||||
+ (query ? `?${query}` : "");
|
||||
return { connectionId: connection.id, provider: sourceTemplateKey ?? "oauth",
|
||||
authorizationUrl: destination, expiresAt: null };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user