Keep agent-owned connections healthy during catalog refresh (#21539)

Use dedicated agent grants for catalog refresh, GitHub health checks, and reconnect status. Preserve shared connection health when a different agent lacks authorization.

Add PostgreSQL and HTTP regressions for credential selection, stale health recovery, caller isolation, and actual provider rejection. Correct the MCP demo approval fixture to submit a valid saved-card option through normal answer validation.

Validation: 629 focused tests, server typecheck, all CI checks, and Greptile 5/5 with no unresolved review comments.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-13 18:45:20 -08:00
1 parent 833689a3fc
commit dc018f9bc0
9 files changed
+284 -12

No files matched your search

@@ -0,0 +1,214 @@
import { randomUUID } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, authUsers, companies, companyMemberships, companySecretBindings, connectionGrants, createDb, principalPermissionGrants, toolApplications, toolCatalogEntries, toolConnections } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { syncConnectionCredentialBindings } from "../services/connection-credential-bindings.js";
import { connectionManagementService } from "../services/connection-management.js";
import { secretService } from "../services/secrets.js";
import { toolAccessService } from "../services/tool-access.js";
import type { PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
describe("dedicated agent connection discovery", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let provider: Server;
let origin: string;
let requests: Array<string | undefined>;
let rejectCredential: boolean;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("agent-connection-catalog-");
db = createDb(database.connectionString);
provider = createServer(async (req, res) => {
if (req.method !== "POST") { res.writeHead(404); res.end(); return; }
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
const message = JSON.parse(Buffer.concat(chunks).toString());
requests.push(req.headers.authorization);
if (rejectCredential || req.headers.authorization !== "Bearer fixture-agent-access") {
res.writeHead(401, { "www-authenticate": "Bearer", "content-type": "application/json" });
res.end(JSON.stringify({ error: "unauthorized" }));
return;
}
if (message.method === "notifications/initialized") {
res.writeHead(202); res.end(); return;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: message.method === "initialize"
? { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } }
: { tools: [{ name: "get_fixture", description: "Read a fixture", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } }] } }));
});
await new Promise<void>(resolve => provider.listen(0, "127.0.0.1", resolve));
origin = `http://127.0.0.1:${(provider.address() as AddressInfo).port}`;
});
beforeEach(() => {
requests = [];
rejectCredential = false;
const localFetch = globalThis.fetch;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href.startsWith(`${origin}/`)) return localFetch(url, init);
if (href === "https://api.github.com/user") return Response.json({ id: 42, login: "fixture-bot" });
if (href.startsWith("https://api.github.com/user/installations?")) return Response.json({ installations: [{ id: 101, repository_selection: "selected", account: { login: "example" } }] });
if (href.startsWith("https://api.github.com/user/installations/101/repositories?")) return Response.json({ total_count: 1, repositories: [{ id: 1, full_name: "example/fixture" }] });
throw new Error("Unexpected provider request");
});
});
afterEach(() => vi.restoreAllMocks());
afterAll(async () => {
if (provider) await new Promise<void>(resolve => provider.close(() => resolve()));
await db?.$client.end({ timeout: 1 });
await database?.cleanup();
});
async function fixture() {
const [company] = await db.insert(companies).values({ name: "Agent catalog fixture", issuePrefix: `AC${randomUUID().slice(0, 6)}` }).returning();
const [agent, otherAgent] = await db.insert(agents).values(["Owner", "Other"].map(name => ({ companyId: company.id, name, role: "engineer", adapterType: "process" }))).returning();
const [application] = await db.insert(toolApplications).values({ companyId: company.id, name: "GitHub", type: "mcp_http" }).returning();
const [connection] = await db.insert(toolConnections).values({
companyId: company.id, applicationId: application.id, name: "GitHub", uid: randomUUID(),
transport: "mcp_remote", authKind: "oauth", credentialPolicy: "per_agent", status: "active", enabled: true,
healthStatus: "failed", healthMessage: "OAuth credentials have expired and need to be reconnected.",
config: { sourceTemplateKey: "github", url: `${origin}/mcp`, oauth: {
strategy: "paperclip_cloud_connector", provider: "github", connectorProfile: "github.code",
tokenUrl: "https://github.com/login/oauth/access_token", expiresAt: null,
} },
}).returning();
const secret = await secretService(db).create(company.id, { name: "Agent access", key: randomUUID(), provider: "local_encrypted", value: "fixture-agent-access" });
const [grant] = await db.insert(connectionGrants).values({
companyId: company.id, connectionId: connection.id, kind: "agent", subjectAgentId: agent.id, status: "active",
credentialSecretRefs: [{ secretId: secret.id, configPath: "oauth.access_token", versionSelector: "latest", required: true }],
providerTenant: { oauth: { strategy: "paperclip_cloud_connector", accessTokenExpiresAt: null },
github: { userId: "42", login: "fixture-bot", installationCount: 1, repositoryCount: 1, repositorySelection: "selected", installationIds: ["101"], installationOwnerLogins: ["example"] } },
}).returning();
await syncConnectionCredentialBindings(db, connection);
const connector = { setWebhookBinding: vi.fn(async () => undefined) } as unknown as PaperclipCloudConnector;
const service = toolAccessService(db, { deploymentMode: "local_trusted", deploymentExposure: "private", paperclipCloudConnector: connector });
return { company, agent, otherAgent, connection, grant, secret, service };
}
it.each(["background", "system", "operator", "agent"] as const)("renames and refreshes an agent-owned GitHub connection without reconnect (%s)", async mode => {
const f = await fixture();
const actor = mode === "background" ? undefined : mode === "system"
? { actorType: "system" as const } : mode === "operator"
? { actorType: "user" as const, actorId: "fixture-operator" }
: { actorType: "agent" as const, actorId: f.agent.id };
await f.service.updateConnection(f.connection.id, { name: "Renamed bot" });
const refreshed = await f.service.refreshCatalog(f.connection.id, actor);
expect(refreshed.connection).toMatchObject({ name: "Renamed bot", healthStatus: "ok", enabled: true });
expect((await f.service.getConnection(f.connection.id, f.company.id)).requiresReauthorization).toBe(false);
expect(refreshed.catalog.map(tool => tool.toolName)).toEqual(["get_fixture"]);
expect(requests.length).toBeGreaterThan(0);
expect(requests.every(header => header === "Bearer fixture-agent-access")).toBe(true);
await expect(f.service.checkHealth(f.connection.id, actor)).resolves.toMatchObject({ connection: { healthStatus: "ok" } });
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, f.grant.id));
expect(grant.status).toBe("active");
expect(grant.credentialSecretRefs).toEqual(f.grant.credentialSecretRefs);
const bindings = await db.select().from(companySecretBindings).where(and(eq(companySecretBindings.targetId, f.connection.id), eq(companySecretBindings.secretId, f.secret.id)));
expect(bindings).toHaveLength(1);
});
describe.each(["refreshCatalog", "checkHealth"] as const)("%s caller isolation", operation => {
it.each(["another agent", "another company", "missing agent identity"])("denies %s without changing the owner's connection", async scope => {
const f = await fixture();
const actorId = scope === "another company" ? (await fixture()).agent.id : scope === "missing agent identity" ? null : f.otherAgent.id;
await f.service.refreshCatalog(f.connection.id, { actorType: "agent", actorId: f.agent.id });
const before = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id));
const catalog = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, f.connection.id));
requests = [];
vi.mocked(fetch).mockClear();
await expect(f.service[operation](f.connection.id, { actorType: "agent", actorId }))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_required" } });
expect(requests).toEqual([]);
expect(fetch).not.toHaveBeenCalled();
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id))).toEqual(before);
expect(await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, f.connection.id))).toEqual(catalog);
await expect(f.service.checkHealth(f.connection.id, { actorType: "agent", actorId: f.agent.id }))
.resolves.toMatchObject({ connection: { healthStatus: "ok" } });
});
it("keeps the owner's tools healthy when a permitted managing agent lacks the credential", async () => {
const f = await fixture();
const userId = randomUUID();
await db.insert(authUsers).values({ id: userId, name: "Manager", email: `${userId}@fixture.invalid`, createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values([
{ companyId: f.company.id, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" },
{ companyId: f.company.id, principalType: "agent", principalId: f.otherAgent.id, status: "active" },
]);
await db.insert(principalPermissionGrants).values([
{ companyId: f.company.id, principalType: "agent", principalId: f.otherAgent.id, permissionKey: "tools:manage_connections" },
{ companyId: f.company.id, principalType: "user", principalId: userId, permissionKey: "tools:manage_connections" },
]);
const managementContext = await connectionManagementService(db).authorize({
type: "agent", agentId: f.otherAgent.id, companyId: f.company.id, onBehalfOfUserId: userId,
}, "connections:configure", { type: "connection_management", companyId: f.company.id, connectionId: f.connection.id, operation });
expect(managementContext.decision.allowed).toBe(true);
await f.service.refreshCatalog(f.connection.id, { actorType: "agent", actorId: f.agent.id });
const before = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id));
requests = [];
vi.mocked(fetch).mockClear();
await expect(f.service[operation](f.connection.id, { actorType: "agent", actorId: f.otherAgent.id, managementContext }))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_required" } });
expect(requests).toEqual([]);
expect(fetch).not.toHaveBeenCalled();
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id))).toEqual(before);
expect((await f.service.listCatalog(f.connection.id, f.company.id)).map(tool => tool.toolName)).toEqual(["get_fixture"]);
});
});
it("does not fall back to personal or organization grants when the agent grant is revoked", async () => {
const f = await fixture();
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.grant.id));
await db.insert(connectionGrants).values([
{ companyId: f.company.id, connectionId: f.connection.id, kind: "organization", status: "active", isDefault: true, credentialSecretRefs: f.grant.credentialSecretRefs },
{ companyId: f.company.id, connectionId: f.connection.id, kind: "user", subjectUserId: "fixture-operator", status: "active", credentialSecretRefs: f.grant.credentialSecretRefs },
]);
await expect(f.service.refreshCatalog(f.connection.id))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_required" } });
await expect(f.service.refreshCatalog(f.connection.id, { actorType: "user", actorId: "fixture-operator" }))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_required" } });
expect((await f.service.getConnection(f.connection.id, f.company.id)).requiresReauthorization).toBe(true);
await expect(f.service.checkHealth(f.connection.id))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_required" } });
expect(requests).toEqual([]);
expect(fetch).not.toHaveBeenCalled();
});
it("uses the same agent grant for generic OAuth MCP health and discovery", async () => {
const f = await fixture();
await f.service.updateConnection(f.connection.id, { config: { url: `${origin}/mcp`, oauth: {
provider: origin, tokenUrl: `${origin}/token`, expiresAt: null,
} } });
await expect(f.service.refreshCatalog(f.connection.id)).resolves.toMatchObject({ connection: { healthStatus: "ok" } });
await expect(f.service.checkHealth(f.connection.id)).resolves.toMatchObject({ connection: { healthStatus: "ok" } });
expect(requests.length).toBeGreaterThan(0);
expect(requests.every(header => header === "Bearer fixture-agent-access")).toBe(true);
});
it("does not choose between multiple active agent authorizations in background work", async () => {
const f = await fixture();
await db.insert(connectionGrants).values({ companyId: f.company.id, connectionId: f.connection.id,
kind: "agent", subjectAgentId: f.otherAgent.id, status: "active", credentialSecretRefs: f.grant.credentialSecretRefs });
await expect(f.service.refreshCatalog(f.connection.id))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_ambiguous" } });
await expect(f.service.checkHealth(f.connection.id))
.rejects.toMatchObject({ status: 422, details: { code: "agent_authorization_ambiguous" } });
expect(requests).toEqual([]);
expect(fetch).not.toHaveBeenCalled();
});
it("still requires reconnect when the provider rejects the agent's credential", async () => {
const f = await fixture();
rejectCredential = true;
await expect(f.service.refreshCatalog(f.connection.id)).rejects.toThrow();
expect(requests.length).toBeGreaterThan(0);
expect(requests.every(header => header === "Bearer fixture-agent-access")).toBe(true);
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, f.grant.id));
expect(grant.status).toBe("needs_reauthorization");
expect((await f.service.getConnection(f.connection.id, f.company.id)).requiresReauthorization).toBe(true);
});
});
@@ -65,6 +65,7 @@ function githubConnectionHealth() {
discovery: {} as never,
setupPolicy: { assertConnectorConnectionSetupEnabled: async () => undefined } as never,
resolveCredentialHeaders: vi.fn() as never,
vaultGrantForConnection: vi.fn() as never,
refreshManagedGitHubGrantAccess: (async () => {
await loadGitHubGrantMetadata("ghu_secret", suspendedGitHub);
}) as never,
@@ -15,10 +15,12 @@ import {
toolMcpTasks,
} from "@paperclipai/db";
import { and, eq, lte, ne } from "drizzle-orm";
import type { AskUserQuestionsPayload } from "@paperclipai/shared";
import { forgetMcpHttpSessions } from "../services/mcp-http.js";
import { createToolGatewayService } from "../services/tool-gateway.js";
import { toolAccessService } from "../services/tool-access.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { adapterExecutionControls, createAdapterExecutionControl } from "../services/adapter-execution-control.js";
import {
createTasksDemoHttpServer,
@@ -144,11 +146,14 @@ const support = await getEmbeddedPostgresTestSupport();
expect(first).toMatchObject({ reasonCode: "elicitation_required" });
const [card] = await db.select().from(issueThreadInteractions).where(and(eq(issueThreadInteractions.companyId, org.id), eq(issueThreadInteractions.issueId, issue.id)));
expect(card).toMatchObject({ kind: "ask_user_questions", status: "pending" });
await db.update(issueThreadInteractions).set({ status: "answered", result: { version: 1, answers: [
{ questionId: "decision", optionIds: ["approve"] },
const decision = (card!.payload as unknown as AskUserQuestionsPayload).questions.find((question) => question.id === "decision")!;
const approve = decision.options.find((option) => option.label === "approve");
expect(approve).toBeDefined();
await issueThreadInteractionService(db).answerQuestions({ id: issue.id, companyId: org.id }, card!.id, { answers: [
{ questionId: decision.id, optionIds: [approve!.id] },
{ questionId: "note", optionIds: [], otherText: "go ahead" },
] } }).where(eq(issueThreadInteractions.id, card!.id));
const pending = call("needs_approval", { action: "rotate the demo key" });
] }, { userId: actor.actorId });
const pending = call("needs_approval", { action: "rotate the demo key" }).catch((error) => error);
await vi.waitFor(() => expect(demoTask("needs_approval")?.status).toBe("working"), { timeout: 5_000 });
clock += 3_000;
expect(await pending).toMatchObject({ status: "completed", result: { content: "Approved: rotate the demo key was carried out. Note: go ahead" } });
+5 -3
View File
@@ -803,7 +803,7 @@ export function toolAccessService(
const defaultCatalogAccess = createCatalogDefaultAccess(db);
const { enableCatalogEntriesByDefault, upsertAskFirstPolicies } = defaultCatalogAccess;
const catalogDiscovery = createToolCatalogDiscovery(db, { now, audit, secrets, credentials: credentialAccess, vercel: vercelCredentials, vercelConnect, setupPolicy, requestRemoteHttpEndpoint, resolveOAuthGrantSecret, discoverOAuthEndpoints, localTools });
const connectionHealth = createConnectionHealth(db, { now, audit, getConnectionRow, discovery: catalogDiscovery, setupPolicy, resolveCredentialHeaders, refreshManagedGitHubGrantAccess, ensureRuntimeSlot, stdioTemplateId });
const connectionHealth = createConnectionHealth(db, { now, audit, getConnectionRow, discovery: catalogDiscovery, setupPolicy, resolveCredentialHeaders, vaultGrantForConnection, refreshManagedGitHubGrantAccess, ensureRuntimeSlot, stdioTemplateId });
const { updateConnectionHealth, checkConnectionHealth, sweepConnectionHealth } = connectionHealth;
const refreshCatalog = createToolCatalogPublication(db, { now, audit, getConnectionRow, discoverTools: catalogDiscovery.discoverTools, discoverSkills: catalogDiscovery.discoverSkills, assertConnectorConnectionSetupEnabled, updateConnectionHealth, vaultGrantForConnection, ensureRuntimeSlot, enableCatalogEntriesByDefault });
const catalogReader = createToolCatalogReader(db, options, now, getConnectionRow, refreshCatalog, toCatalogEntryForConnection);
@@ -1065,8 +1065,10 @@ export function toolAccessService(
const eligible = grants.filter(
(grant) =>
grant.connectionId === connection.id &&
(connection.credentialPolicy !== "per_user" ||
(grant.kind === "user" && grant.subjectUserId === userId)),
(connection.credentialPolicy === "per_agent"
? grant.kind === "agent"
: connection.credentialPolicy !== "per_user" ||
(grant.kind === "user" && grant.subjectUserId === userId)),
);
connection.requiresReauthorization = !eligible.some(
(grant) => grant.status === "active",
@@ -20,6 +20,12 @@ export function isOAuthEndpointRejection(error: unknown): boolean {
return typeof code === "string" && code.endsWith("_endpoint_rejected");
}
/** A caller without an agent grant has not tested the connection's credential. */
export function isCallerAuthorizationFailure(error: unknown, actor?: ActorInfo): boolean {
return actor?.actorType === "agent" && error instanceof HttpError
&& asRecord(error.details).code === "agent_authorization_required";
}
export function healthFailureHttpStatus(failure: {
status: ToolConnectionHealthStatus;
code: string;
@@ -31,6 +37,7 @@ export function healthFailureHttpStatus(failure: {
if (failure.code === "oauth_insufficient_scope") return 422;
if (failure.code === "slack_mcp_access_disabled") return 422;
if (failure.code === "user_authorization_required") return 422;
if (failure.code === "agent_authorization_required" || failure.code === "agent_authorization_ambiguous") return 422;
if (failure.code === "github_installation_required") return 422;
if (failure.code === "composio_broker_retired") return 422;
if (failure.code === "tool_connection_transport_unsupported") return 422;
@@ -62,7 +69,8 @@ export function sanitizeHttpFailure(error: unknown): {
if (code === "slack_mcp_access_disabled" || code === "google_workspace_services_unavailable") {
return { status: "error", message: error.message, code };
}
if (code === "user_authorization_required" || code === "github_installation_required") {
if (code === "user_authorization_required" || code === "agent_authorization_required"
|| code === "agent_authorization_ambiguous" || code === "github_installation_required") {
return { status: "error", message: error.message, code };
}
if (code === "tool_connection_transport_unsupported") {
@@ -21,7 +21,7 @@ import type { ConnectionCredentialAccess } from "../credential-access.js";
import type { ConnectionSetupPolicy } from "../connections/setup-policy.js";
import { toConnection } from "../connections/projection.js";
import { isAgentMailConnection, type ToolCatalogDiscovery } from "./discovery.js";
import { healthFailureHttpStatus, sanitizeHttpFailure, unreachableServerRemediation, unsupportedToolConnectionTransport } from "./failures.js";
import { healthFailureHttpStatus, isCallerAuthorizationFailure, sanitizeHttpFailure, unreachableServerRemediation, unsupportedToolConnectionTransport } from "./failures.js";
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === "object" && !Array.isArray(value))
return value as Record<string, unknown>;
@@ -35,12 +35,13 @@ type HealthDependencies = {
discovery: ToolCatalogDiscovery;
setupPolicy: ConnectionSetupPolicy;
resolveCredentialHeaders: ConnectionCredentialAccess["resolveCredentialHeaders"];
vaultGrantForConnection: ConnectionCredentialAccess["vaultGrantForConnection"];
refreshManagedGitHubGrantAccess: ReturnType<typeof createGitHubGrantContinuity>["refreshManagedGitHubGrantAccess"];
ensureRuntimeSlot: ReturnType<typeof createToolRuntimeSlots>["ensureRuntimeSlot"];
stdioTemplateId(companyId: string, config: Record<string, unknown>): Promise<string>;
};
export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, discovery, setupPolicy, resolveCredentialHeaders, refreshManagedGitHubGrantAccess, ensureRuntimeSlot, stdioTemplateId }: HealthDependencies) {
export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, discovery, setupPolicy, resolveCredentialHeaders, vaultGrantForConnection, refreshManagedGitHubGrantAccess, ensureRuntimeSlot, stdioTemplateId }: HealthDependencies) {
const { discoverTools, remoteTools, validateAgentMailConnection, validateCogneeConnection } = discovery;
const { assertConnectorConnectionSetupEnabled } = setupPolicy;
async function updateConnectionHealth(
@@ -94,7 +95,9 @@ export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, d
config.sourceTemplateKey === "github" &&
oauth.connectorProfile === "github.code"
) {
const activeGrants = await db
const activeGrants = connection.credentialPolicy === "per_agent"
? [await vaultGrantForConnection(connection, actor)].filter(grant => grant !== null)
: await db
.select()
.from(connectionGrants)
.where(
@@ -187,6 +190,7 @@ export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, d
});
return { connection: toConnection(updated), runtimeSlot };
} catch (error) {
if (isCallerAuthorizationFailure(error, actor)) throw error;
if (
error instanceof HttpError &&
asRecord(error.details).code === "github_access_changed"
@@ -29,7 +29,7 @@ import { isAgentMailConnection, type ToolCatalogDiscovery } from "./discovery.js
import { classifyRisk, shouldQuarantineNewEntries, isGoogleWorkspaceToolAllowed, type McpToolDescriptor } from "./descriptors.js";
import { toConnection } from "../connections/projection.js";
import { toCatalogEntry } from "./projection.js";
import { healthFailureHttpStatus, sanitizeHttpFailure, unreachableServerRemediation } from "./failures.js";
import { healthFailureHttpStatus, isCallerAuthorizationFailure, sanitizeHttpFailure, unreachableServerRemediation } from "./failures.js";
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === "object" && !Array.isArray(value))
return value as Record<string, unknown>;
@@ -94,6 +94,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection
unavailableServices,
);
} catch (error) {
if (isCallerAuthorizationFailure(error, actor)) throw error;
if (
error instanceof HttpError &&
asRecord(error.details).code === "github_access_changed"
@@ -39,6 +39,33 @@ export function createConnectionCredentialAccess(db: Db, { secrets, audit, verce
connection: typeof toolConnections.$inferSelect,
actor?: ActorInfo,
): Promise<typeof connectionGrants.$inferSelect | null> {
if (connection.credentialPolicy === "per_agent") {
const agentId = actor?.actorType === "agent" ? actor.actorId : null;
if (actor?.actorType === "agent" && !agentId) {
throw unprocessable("This connection needs the agent's authorization", {
code: "agent_authorization_required",
});
}
// Discovery has no run identity in background/operator work. Use only
// an unambiguous active agent grant; an agent caller must use its own.
const grants = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.kind, "agent"),
eq(connectionGrants.status, "active"),
...(agentId ? [eq(connectionGrants.subjectAgentId, agentId)] : []),
)).limit(2);
if (grants.length !== 1) {
throw unprocessable(grants.length > 1
? "This connection has multiple agent accounts. Use a separate connection for each agent."
: "This connection needs the agent's authorization", {
code: grants.length > 1 ? "agent_authorization_ambiguous" : "agent_authorization_required",
setupUrl: connectionSetupUrl(connection),
reconnectUrl: connectionReconnectUrl(connection),
});
}
return grants[0]!;
}
const actorUserId =
connectionActorUserId(actor);
if (actorUserId) {