Files
PaperClipAI/server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts
T
Dotta 263c6f6c04 fix(tool-access): enforce connection installs across non-plugin transports (#22967)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call external tools (remote MCP, OAuth REST apps, local
stdio, plugins) through Paperclip's tool-access policy, Effective Access
view, and tool gateway
> - Non-plugin connections installed only for Agent A could still be
called by Agent B because `tool-access-policy.ts` only checked
`tool_connection_installs` for `plugin` connections,
`governedByConnectionProfile` only checked the calling agent's own bound
profiles (allowing Agent B's default unscoped `tools:use` grant to
match), Effective Access did not filter by connection installs, and
reconnect/uninstall paths could drop agent scoping
> - This is a cross-agent security boundary bypass where an agent can
access another agent's private connection or mailbox
> - This pull request extracts one shared `connection-access-boundary`
helper and enforces connection install boundaries consistently across
policy decisions, Effective Access (`allowedTools` and profile summary
counts), install removal (`putConnectionInstalls`), generic approval
policies, and gallery reconnect/catalog sync while preserving legacy
shared connections and explicit policy/targeted-grant overrides
> - The benefit is airtight per-agent connection isolation across all
transports with policy/test, Effective Access, and the live tool gateway
in full agreement

## Linked Issues or Issue Description

- Fixes: #17166

## What Changed

- **`server/src/services/tool-access/connection-access-boundary.ts`**:
Extracted a single shared batched helper
(`readConnectionAccessBoundaries`, `connectionRequiresInstall`,
`hasAgentAccessConfiguredMarker`, `agentAccessConfiguredSql`,
`defaultConnectionProfileBindingTargets`) so policy evaluation,
Effective Access projection, and default binding helpers share one query
and predicate.
- **`server/src/services/tool-access-policy.ts`**:
- Keeps the pre-policy install gate for `plugin` connections unchanged.
- Enforces the shared connection install boundary for non-plugin
governed connections (any connection with `tool_connection_installs`
rows, `agentAccessConfigured` / `mcpAgentAccessConfigured` marker, or
unbound managed profiles): denies uninstalled agents with
`deny_connection_not_installed` before profile/trust allows and blocks
generic `require_approval` policies when `blockedByConnectionInstall` is
true (so pending approvals cannot execute after uninstall and cannot
fall through to lower-priority allow policies), while preserving
explicit `block`/`allow` policies and tool-targeted `tools:use` grants
(`scope: { connectionId }`, `{ allow: [...] }`, etc.) required by
delegated policy contracts.
- Rejects default unscoped `tools:use` (`scope: null`) whenever the
connection is governed by installs or managed connection profiles, and
suppresses `app_gallery_finish` / `connection_intent` approval and trust
rules for uninstalled agents.
- Preserves legacy company-wide / unscoped connections that have no
install rows, no `agentAccessConfigured` marker, and no unbound managed
profiles.
- **`server/src/services/tool-access/profiles/resolution.ts`**: Uses
`readConnectionAccessBoundaries` to filter Effective Access
`allowedTools` and passes `eligibleCatalog` to `buildProfileDetails` so
`profile.summary.allowedToolCount` agrees with `allowedTools` and `POST
/companies/:companyId/tools/policy/test`.
- **`server/src/services/tool-access/connections/installs.ts` &
`server/src/services/tool-access.ts`**:
- Persists `agentAccessConfigured: true` on all governed tool
connections when installs are saved via `putConnectionInstalls` or
`finishGalleryAppConnection` (alongside `mcpAgentAccessConfigured: true`
for `mcp_remote`), so removing the final install via
`putConnectionInstalls({ installs: [] })` closes access across
`mcp_remote`, `rest_api`, and `local_stdio`.
- Preserves `agentAccessConfigured` / `mcpAgentAccessConfigured` on
`connectGalleryApp` reconnect when the retained connection is not
`archived` (while allowing revival of an archived connection to restore
fresh defaults).
- **`server/src/services/tool-access/catalog/default-access.ts` &
`server/src/services/tool-access/oauth/catalog-completion.ts`**: Uses
`defaultConnectionProfileBindingTargets` and
`hasAgentAccessConfiguredMarker` so reconnecting or syncing catalog
tools preserves existing agent-scoped installs and zero-agent
restrictions without widening access to the whole company.
- **Tests (`server/src/__tests__/tool-access-policy-service.test.ts`,
`heartbeat-runtime-mcp-servers.test.ts`,
`tool-access-policy-index.test.ts`)**: Added RED-before-fix regression
tests and embedded-Postgres route/gateway E2E coverage across
`mcp_remote`, `rest_api`, and `local_stdio`, newly created Agent C,
stripped-marker zero-agent removal via `putConnectionInstalls({
installs: [] })`, generic `require_approval` + explicit
allow/targeted-grant precedence, reconnect preservation, Effective
Access profile summary counts, and legacy shared connections.

## Verification

- Verified RED-before-fix on base `2d06567795`: `pnpm --filter
@paperclipai/server exec vitest run
src/__tests__/tool-access-policy-service.test.ts -t "denies uninstalled
agents|aligns policy/test route"` failed 4/4 with uninstalled agents
receiving `allow_explicit_grant`.
- Verified GREEN-after-fix on `484ecb416a`:
  - `pnpm --filter @paperclipai/server typecheck` (PASS, all 7 layers)
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/tool-access-policy-service.test.ts` (PASS)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-policy-service.test.ts
src/__tests__/connection-management-delegated-policy.integration.test.ts
src/__tests__/plugin-connector-install-gate.test.ts` (3 files, 100/100
tests PASS)
- Full Paperclip CI (`66/66` executed checks PASS) + Greptile **5/5**
(`0` unresolved review threads)

## Risks

- Low risk: legacy unscoped/company-wide connections with no
`tool_connection_installs` rows, no `agentAccessConfigured` /
`mcpAgentAccessConfigured` marker, and no unbound managed connection
profiles continue to evaluate unchanged.
- Explicit `block`/`allow` policies and tool-targeted `tools:use` grants
continue to take precedence over the non-plugin install gate (matching
`connection-management-delegated-policy.integration.test.ts`), while
default unscoped `tools:use` (`scope: null`), generic
`require_approval`, and profile/trust allows can no longer bypass
connection install boundaries.

## Model Used

- Google Gemini (Antigravity agentic workflow with tool use, code
execution, and embedded-Postgres verification)

## 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
- [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
2026-11-25 15:32:01 -06:00

895 lines
39 KiB
TypeScript

import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { mcpGatewayProtocolRoutes } from "../routes/tool-gateway.js";
import { eq, like, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
activityLog,
companies,
companyMemberships,
connectionGrants,
createDb,
heartbeatRuns,
toolAccessAuditEvents,
toolApplications,
toolConnectionInstalls,
toolConnections,
toolCatalogEntries,
toolMcpGateways,
toolMcpGatewayTokens,
toolProfileBindings,
toolProfileEntries,
toolProfiles,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { buildPaperclipRuntimeMcpServers, createManagedMcpRunConfig } from "../services/heartbeat.js";
import { createToolGatewayService, ToolGatewayHttpError } from "../services/tool-gateway.js";
import { toolAccessService } from "../services/tool-access.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("heartbeat runtime MCP servers", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const originalApiUrl = process.env.PAPERCLIP_API_URL;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-runtime-mcp-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
if (originalApiUrl === undefined) delete process.env.PAPERCLIP_API_URL;
else process.env.PAPERCLIP_API_URL = originalApiUrl;
await db.delete(toolMcpGatewayTokens);
await db.delete(activityLog);
await db.delete(toolAccessAuditEvents);
await db.delete(heartbeatRuns);
await db.delete(toolMcpGateways);
await db.delete(connectionGrants);
await db.delete(toolConnectionInstalls);
await db.delete(toolProfileBindings);
await db.delete(toolProfileEntries);
await db.delete(toolProfiles);
await db.delete(toolConnections);
await db.delete(toolApplications);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
it("provisions one aggregate gateway and omits unavailable access without blocking any runtime", async () => {
process.env.PAPERCLIP_API_URL = "https://paperclip.example.test";
const [company] = await db.insert(companies).values({
name: `Runtime MCP ${randomUUID()}`,
issuePrefix: `RM${randomUUID().slice(0, 5).toUpperCase()}`,
}).returning();
const [agent] = await db.insert(agents).values({
companyId: company!.id,
name: "Runtime MCP Agent",
role: "engineer",
adapterType: "codex_local",
adapterConfig: {},
}).returning();
const [application] = await db.insert(toolApplications).values({
companyId: company!.id,
applicationKey: `runtime-${randomUUID().slice(0, 8)}`,
name: "Runtime MCP App",
type: "mcp_http",
status: "active",
}).returning();
const [installedConnection, uninstalledConnection] = await db.insert(toolConnections).values([
{
companyId: company!.id,
applicationId: application!.id,
name: "Installed MCP",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
config: { url: "https://installed.example.test/mcp" },
},
{
companyId: company!.id,
applicationId: application!.id,
name: "Uninstalled MCP",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
config: { url: "https://uninstalled.example.test/mcp" },
},
]).returning();
const [profile] = await db.insert(toolProfiles).values({
companyId: company!.id,
profileKey: `app:${installedConnection!.id}`,
name: "Installed MCP",
defaultAction: "deny",
}).returning();
await db.insert(toolProfileEntries).values({
companyId: company!.id,
profileId: profile!.id,
selectorType: "connection",
effect: "include",
applicationId: application!.id,
connectionId: installedConnection!.id,
});
await db.insert(toolProfileBindings).values({
companyId: company!.id,
profileId: profile!.id,
targetType: "agent",
targetId: agent!.id,
});
await db.insert(toolConnectionInstalls).values({
companyId: company!.id,
connectionId: installedConnection!.id,
targetType: "agent",
targetId: agent!.id,
});
const before = Date.now();
const first = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: randomUUID() });
const second = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: randomUUID() });
expect(first).toHaveLength(1);
expect(first[0]).toMatchObject({
name: "paperclip-assigned",
connectionId: expect.stringMatching(/^assignment:[a-f0-9]{64}$/),
url: expect.stringMatching(/^https:\/\/paperclip\.example\.test\/mcp\/gateways\/gw_[a-f0-9]{32}$/),
token: expect.stringMatching(/^pcgw_/),
});
expect(JSON.stringify(first)).not.toContain(uninstalledConnection!.id);
expect(second).toHaveLength(1);
expect(second[0]!.connectionId).toBe(first[0]!.connectionId);
const gateways = await db.select().from(toolMcpGateways);
expect(gateways).toHaveLength(1);
// The column, not metadata, is what named-gateway auth checks run tokens against.
expect(gateways[0]!.agentId).toBe(agent!.id);
expect(gateways[0]!.metadata).toMatchObject({
nativeRuntimeAssignmentDigest: first[0]!.connectionId.slice("assignment:".length),
agentId: agent!.id,
});
const tokens = await db.select().from(toolMcpGatewayTokens);
expect(tokens).toHaveLength(2);
for (const token of tokens) {
expect(token.subjectType).toBe("heartbeat_run");
expect(token.subjectId).toMatch(/^[0-9a-f-]{36}$/);
expect(token.expiresAt!.getTime()).toBeGreaterThanOrEqual(before + 59 * 60 * 1000);
expect(token.expiresAt!.getTime()).toBeLessThanOrEqual(Date.now() + 61 * 60 * 1000);
}
expect(JSON.stringify(tokens)).not.toContain(first[0]!.token);
await expect(
buildPaperclipRuntimeMcpServers({
db,
agent: agent!,
runId: randomUUID(),
expectedAssignmentDigest: "0".repeat(64),
}),
).resolves.toEqual([]);
expect(await db.select().from(toolMcpGatewayTokens)).toHaveLength(2);
await db.update(toolConnections)
.set({ healthStatus: "degraded", healthMessage: "fixture unavailable" })
.where(eq(toolConnections.id, installedConnection!.id));
await expect(
buildPaperclipRuntimeMcpServers({
db,
agent: agent!,
runId: randomUUID(),
expectedAssignmentDigest: first[0]!.connectionId.slice("assignment:".length),
}),
).resolves.toEqual([]);
expect(await db.select().from(toolMcpGatewayTokens)).toHaveLength(2);
await expect(
createManagedMcpRunConfig({
db,
agent: agent!,
runId: randomUUID(),
config: {},
projectId: null,
issueId: null,
}),
).resolves.toBeNull();
});
async function seedAssignedAgents(count: number) {
process.env.PAPERCLIP_API_URL = "https://paperclip.example.test";
const [company] = await db.insert(companies).values({
name: `Runtime MCP ${randomUUID()}`,
issuePrefix: `RM${randomUUID().slice(0, 5).toUpperCase()}`,
}).returning();
const [application] = await db.insert(toolApplications).values({
companyId: company!.id,
applicationKey: `runtime-${randomUUID().slice(0, 8)}`,
name: "Runtime MCP App",
type: "mcp_http",
status: "active",
}).returning();
const [connection] = await db.insert(toolConnections).values({
companyId: company!.id,
applicationId: application!.id,
name: "Installed MCP",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
config: { url: "https://installed.example.test/mcp" },
}).returning();
const [profile] = await db.insert(toolProfiles).values({
companyId: company!.id,
profileKey: `app:${connection!.id}`,
name: "Installed MCP",
defaultAction: "deny",
}).returning();
await db.insert(toolProfileEntries).values({
companyId: company!.id,
profileId: profile!.id,
selectorType: "connection",
effect: "include",
applicationId: application!.id,
connectionId: connection!.id,
});
const seeded = [];
for (let index = 0; index < count; index += 1) {
const [agent] = await db.insert(agents).values({
companyId: company!.id,
name: `Runtime MCP Agent ${index}`,
role: "engineer",
adapterType: "codex_local",
adapterConfig: {},
}).returning();
await db.insert(toolProfileBindings).values({
companyId: company!.id,
profileId: profile!.id,
targetType: "agent",
targetId: agent!.id,
});
await db.insert(toolConnectionInstalls).values({
companyId: company!.id,
connectionId: connection!.id,
targetType: "agent",
targetId: agent!.id,
});
const [run] = await db.insert(heartbeatRuns).values({
companyId: company!.id,
agentId: agent!.id,
status: "running",
contextSnapshot: {},
}).returning();
seeded.push({ agent: agent!, run: run! });
}
return seeded;
}
it("waits for the complete native profile when two runs first use the same assignment", async () => {
const [owner] = await seedAssignedAgents(1);
const [next] = await db.insert(heartbeatRuns).values({
companyId: owner!.agent.companyId,
agentId: owner!.agent.id,
status: "running",
}).returning();
const locked = Promise.withResolvers<void>();
const release = Promise.withResolvers<void>();
const blocker = db.transaction(async (tx) => {
await tx.execute(sql`lock table tool_profile_entries in share mode`);
locked.resolve();
await release.promise;
});
blocker.catch(locked.reject);
const pending: ReturnType<typeof buildPaperclipRuntimeMcpServers>[] = [];
const start = (runId: string) => {
const admission = buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId });
pending.push(admission);
void admission.catch(() => {});
};
try {
await locked.promise;
start(owner!.run.id);
await vi.waitFor(async () => {
const waits = await db.execute(sql`select 1 from pg_stat_activity where datname = current_database()
and wait_event_type = 'Lock' and query like 'insert into "tool_profile_entries"%'`);
expect(waits.length).toBe(1);
});
start(next.id);
await vi.waitFor(async () => {
const waits = await db.execute(sql`select 1 from pg_stat_activity where datname = current_database()
and wait_event_type = 'Lock' and query like 'insert into "tool_profiles"%'`);
expect(waits.length).toBe(1);
});
expect(await db.select().from(toolProfiles).where(like(toolProfiles.profileKey, "native:%"))).toEqual([]);
expect(await db.select().from(toolMcpGateways)).toEqual([]);
expect(await db.select().from(toolMcpGatewayTokens)).toEqual([]);
} finally {
release.resolve();
await blocker;
await Promise.allSettled(pending);
}
const [[first], [second]] = await Promise.all(pending);
expect(first!.url).toBe(second!.url);
expect(first!.token).not.toBe(second!.token);
const profiles = await db.select().from(toolProfiles).where(like(toolProfiles.profileKey, "native:%"));
expect(profiles).toHaveLength(1);
expect(await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, profiles[0]!.id))).toHaveLength(1);
expect(await db.select().from(toolMcpGateways)).toHaveLength(1);
expect(await db.select().from(toolMcpGatewayTokens)).toHaveLength(2);
});
it("rolls back native profile creation when writing its entries fails and retries cleanly", async () => {
const [owner] = await seedAssignedAgents(1);
const build = () => buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
await db.execute(sql`alter table tool_profile_entries add constraint fixture_reject_new_profile_entries check (false) not valid`);
try {
await expect(build()).rejects.toMatchObject({ cause: { constraint_name: "fixture_reject_new_profile_entries" } });
expect(await db.select().from(toolProfiles).where(like(toolProfiles.profileKey, "native:%"))).toEqual([]);
expect(await db.select().from(toolMcpGateways)).toEqual([]);
expect(await db.select().from(toolMcpGatewayTokens)).toEqual([]);
} finally {
await db.execute(sql`alter table tool_profile_entries drop constraint fixture_reject_new_profile_entries`);
}
expect(await build()).toHaveLength(1);
const profiles = await db.select().from(toolProfiles).where(like(toolProfiles.profileKey, "native:%"));
expect(profiles).toHaveLength(1);
expect(await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, profiles[0]!.id))).toHaveLength(1);
expect(await db.select().from(toolMcpGatewayTokens)).toHaveLength(1);
});
it("rejects another agent's run token on a run-scoped gateway", async () => {
const [owner, other] = await seedAssignedAgents(2);
const [server] = await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
const [gateway] = await db.select().from(toolMcpGateways);
const service = createToolGatewayService(db);
const otherToken = await service.createNamedGatewayToken({
companyId: owner!.agent.companyId,
gatewayId: gateway!.id,
body: {
name: "Other agent run",
subjectType: "heartbeat_run",
subjectId: other!.run.id,
clientLabel: "Runtime MCP test client",
ownerNote: "",
allowedActions: ["tools/list", "tools/call"],
expiresAt: new Date(Date.now() + 60_000),
},
actor: { agentId: other!.agent.id },
});
await expect(
service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: server!.token }),
).resolves.toMatchObject({ agentId: owner!.agent.id, runId: owner!.run.id });
const rejection = await service
.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: otherToken.token })
.catch((error: unknown) => error);
expect(rejection).toBeInstanceOf(ToolGatewayHttpError);
expect((rejection as ToolGatewayHttpError).reasonCode).toBe("gateway_token_run_context_invalid");
});
it("binds a reused run-scoped gateway that was created without an agent", async () => {
const [owner] = await seedAssignedAgents(1);
await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
// Simulate a gateway provisioned before the agentId column was set.
await db.update(toolMcpGateways).set({ agentId: null });
await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
const gateways = await db.select().from(toolMcpGateways);
expect(gateways).toHaveLength(1);
expect(gateways[0]!.agentId).toBe(owner!.agent.id);
});
it("rejects another run on a legacy native gateway before the owner runs again", async () => {
const [owner, other] = await seedAssignedAgents(2);
const [server] = await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
const [gateway] = await db.select().from(toolMcpGateways);
await db.update(toolMcpGateways).set({ agentId: null }).where(eq(toolMcpGateways.id, gateway!.id));
const service = createToolGatewayService(db);
const token = await service.createNamedGatewayToken({
companyId: owner!.agent.companyId, gatewayId: gateway!.id,
body: { name: "Other run", subjectType: "heartbeat_run", subjectId: other!.run.id, clientLabel: "Runtime MCP test client", ownerNote: "",
allowedActions: ["tools/list"], expiresAt: new Date(Date.now() + 60_000) },
actor: { agentId: other!.agent.id },
});
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: server!.token }))
.resolves.toMatchObject({ agentId: owner!.agent.id });
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: token.token }))
.rejects.toMatchObject({ reasonCode: "gateway_token_run_context_invalid" });
const app = express().use(express.json()).use(mcpGatewayProtocolRoutes(service));
const initialize = (bearer: string) => request(app).post(`/mcp/gateways/${gateway!.gatewayPublicId}`)
.set("Authorization", `Bearer ${bearer}`).send({ jsonrpc: "2.0", id: 1, method: "initialize" });
await initialize(server!.token).expect(200);
await initialize(token.token).expect(401);
await db.update(toolMcpGateways).set({ metadata: { nativeRuntimeAssignmentDigest: "invalid" } })
.where(eq(toolMcpGateways.id, gateway!.id));
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: server!.token }))
.rejects.toMatchObject({ reasonCode: "gateway_token_run_context_invalid" });
await db.update(toolMcpGateways).set({ metadata: gateway!.metadata }).where(eq(toolMcpGateways.id, gateway!.id));
await db.update(toolProfiles).set({ metadata: {} }).where(eq(toolProfiles.id, gateway!.profileId));
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: server!.token }))
.rejects.toMatchObject({ reasonCode: "gateway_token_run_context_invalid" });
});
it("rejects a legacy native gateway with cleared metadata and omits it from managed discovery", async () => {
const [owner, other] = await seedAssignedAgents(2);
const [server] = await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
const [gateway] = await db.select().from(toolMcpGateways);
await db.update(toolMcpGateways).set({ agentId: null, contextScopeType: "none", contextScopeId: null, metadata: {} })
.where(eq(toolMcpGateways.id, gateway!.id));
const service = createToolGatewayService(db);
const token = await service.createNamedGatewayToken({
companyId: owner!.agent.companyId, gatewayId: gateway!.id,
body: { name: "Other run", subjectType: "heartbeat_run", subjectId: other!.run.id, clientLabel: "Runtime MCP test client", ownerNote: "",
allowedActions: ["tools/list"], expiresAt: new Date(Date.now() + 60_000) },
actor: { agentId: other!.agent.id },
});
for (const bearerToken of [token.token, server!.token]) {
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken }))
.rejects.toMatchObject({ reasonCode: "gateway_token_run_context_invalid" });
}
for (const { agent, run } of [owner!, other!]) {
await expect(createManagedMcpRunConfig({ db, agent, runId: run.id, config: {}, projectId: null, issueId: null }))
.resolves.toBeNull();
}
// The immutable profile key still identifies the assignment if its metadata
// is also damaged. Neither authentication nor managed delivery can widen it.
await db.update(toolProfiles).set({ metadata: {} }).where(eq(toolProfiles.id, gateway!.profileId));
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: token.token }))
.rejects.toMatchObject({ reasonCode: "gateway_token_run_context_invalid" });
await expect(createManagedMcpRunConfig({ db, agent: other!.agent, runId: other!.run.id,
config: {}, projectId: null, issueId: null })).resolves.toBeNull();
});
it("rejects JSON null profile metadata with an HTTP authentication response", async () => {
const [owner] = await seedAssignedAgents(1);
const [server] = await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
const [gateway] = await db.select().from(toolMcpGateways);
await db.update(toolProfiles).set({ metadata: sql`'null'::jsonb` }).where(eq(toolProfiles.id, gateway!.profileId));
const service = createToolGatewayService(db);
await expect(service.initializeNamedGatewayProtocol({ gatewayId: gateway!.id, bearerToken: server!.token }))
.rejects.toMatchObject({ reasonCode: "gateway_token_run_context_invalid" });
const app = express().use(express.json()).use(mcpGatewayProtocolRoutes(service));
await request(app).post(`/mcp/gateways/${gateway!.gatewayPublicId}`)
.set("Authorization", `Bearer ${server!.token}`).send({ jsonrpc: "2.0", id: 1, method: "initialize" }).expect(401);
});
it("delivers native assignments once and preserves explicit shared gateways", async () => {
const [owner, other] = await seedAssignedAgents(2);
const native = await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
expect(native).toHaveLength(1);
const [gateway] = await db.select().from(toolMcpGateways);
// All assignment history, including gateways written before owner columns
// existed, belongs to the native delivery path rather than managed config.
await db.update(toolMcpGateways).set({ agentId: null, contextScopeType: "none", contextScopeId: null });
for (const agent of [owner!.agent, other!.agent]) {
await expect(createManagedMcpRunConfig({ db, agent, runId: owner!.run.id, config: {}, projectId: null, issueId: null }))
.resolves.toBeNull();
}
const [sharedProfile] = await db.insert(toolProfiles).values({
companyId: owner!.agent.companyId, profileKey: `shared:${randomUUID()}`,
name: "Explicit shared profile", defaultAction: "deny",
}).returning();
const [nativeEntry] = await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, gateway!.profileId));
await db.insert(toolProfileEntries).values({
companyId: owner!.agent.companyId, profileId: sharedProfile!.id, selectorType: "connection", effect: "include",
applicationId: nativeEntry!.applicationId, connectionId: nativeEntry!.connectionId,
});
const service = createToolGatewayService(db);
const shared = await service.createNamedGateway({
companyId: owner!.agent.companyId,
body: { name: "Explicit company gateway", slug: `shared-${randomUUID()}`, profileId: sharedProfile!.id,
defaultProfileMode: "gateway_only" },
actor: { agentId: owner!.agent.id },
});
const managed = await createManagedMcpRunConfig({ db, agent: other!.agent, runId: other!.run.id,
config: {}, projectId: null, issueId: null });
expect(managed?.gateways.map((entry) => entry.id)).toEqual([shared.id]);
const token = await service.createNamedGatewayToken({
companyId: owner!.agent.companyId, gatewayId: shared.id,
body: { name: "Shared run", subjectType: "heartbeat_run", subjectId: other!.run.id, clientLabel: "Runtime MCP test client", ownerNote: "",
allowedActions: ["tools/list"], expiresAt: new Date(Date.now() + 60_000) },
actor: { agentId: other!.agent.id },
});
await expect(service.initializeNamedGatewayProtocol({ gatewayId: shared.id, bearerToken: token.token }))
.resolves.toMatchObject({ agentId: other!.agent.id });
});
it("does not repair a gateway with conflicting ownership metadata", async () => {
const [owner, other] = await seedAssignedAgents(2);
const [server] = await buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id });
await db.update(toolMcpGateways).set({ agentId: null,
metadata: { nativeRuntimeAssignmentDigest: server!.connectionId.slice("assignment:".length), agentId: other!.agent.id } });
await expect(buildPaperclipRuntimeMcpServers({ db, agent: owner!.agent, runId: owner!.run.id }))
.rejects.toThrow("Invalid native runtime gateway provenance");
const [gateway] = await db.select().from(toolMcpGateways);
expect(gateway!.agentId).toBeNull();
});
it("preserves exact permissions when an aggregate assignment exceeds the public 250-entry edit limit", async () => {
process.env.PAPERCLIP_API_URL = "https://paperclip.example.test";
const [company] = await db.insert(companies).values({
name: "Large MCP assignment",
issuePrefix: `LM${randomUUID().slice(0, 5).toUpperCase()}`,
}).returning();
const [agent, gatewayReader] = await db.insert(agents).values([
{ companyId: company!.id, name: "Cursor Cloud", role: "engineer", adapterType: "cursor_cloud" },
{ companyId: company!.id, name: "Gateway reader", role: "engineer", adapterType: "cursor_cloud" },
]).returning();
const [application] = await db.insert(toolApplications).values({
companyId: company!.id, applicationKey: "large-mcp", name: "Large MCP", type: "mcp_http",
}).returning();
const [connection] = await db.insert(toolConnections).values({
companyId: company!.id, applicationId: application!.id,
name: "Large MCP", uid: `test/${randomUUID()}`, transport: "mcp_remote", status: "active", enabled: true,
config: { url: "https://large.example.test/mcp" },
}).returning();
const catalogInput = (name: string) => ({
companyId: company!.id, applicationId: application!.id, connectionId: connection!.id,
name, toolName: name, versionHash: "fixture", status: "active" as const,
});
const catalog = await db.insert(toolCatalogEntries).values([
...Array.from({ length: 251 }, (_, index) => catalogInput(`allowed_${index}`)),
catalogInput("excluded"), catalogInput("unassigned"),
]).returning();
const allowed = catalog.slice(0, 251);
const excluded = catalog[251]!;
// Multiple valid profiles can each have fewer than 250 entries while their
// union exceeds the HTTP edit-request limit.
const profiles = await db.insert(toolProfiles).values(["first", "second"].map((key) => ({
companyId: company!.id, profileKey: key, name: key, defaultAction: "deny" as const,
}))).returning();
await db.insert(toolProfileEntries).values([
...[...allowed, excluded].map((tool, index) => ({
companyId: company!.id, profileId: profiles[index < 200 ? 0 : 1]!.id,
selectorType: "catalog_entry" as const, effect: "include" as const,
applicationId: application!.id, connectionId: connection!.id, catalogEntryId: tool.id,
})),
{
companyId: company!.id, profileId: profiles[1]!.id,
selectorType: "catalog_entry" as const, effect: "exclude" as const,
applicationId: application!.id, connectionId: connection!.id, catalogEntryId: excluded.id,
},
]);
await db.insert(toolProfileBindings).values(profiles.map((profile) => ({
companyId: company!.id, profileId: profile.id, targetType: "agent" as const, targetId: agent!.id,
})));
await db.insert(toolConnectionInstalls).values({
companyId: company!.id, connectionId: connection!.id, targetType: "agent", targetId: agent!.id,
});
const servers = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: randomUUID() });
expect(servers).toHaveLength(1);
const [gateway] = await db.select().from(toolMcpGateways);
const generatedEntries = await db.select().from(toolProfileEntries)
.where(eq(toolProfileEntries.profileId, gateway!.profileId!));
expect(generatedEntries).toHaveLength(251);
expect(generatedEntries.every((entry) => entry.selectorType === "catalog_entry")).toBe(true);
expect(generatedEntries.map((entry) => entry.catalogEntryId).sort()).toEqual(allowed.map((tool) => tool.id).sort());
// Evaluate the generated profile independently of the original assignments,
// including a tool discovered after the immutable profile was created.
await db.insert(toolCatalogEntries).values(catalogInput("new_after_snapshot"));
await db.insert(toolProfileBindings).values({
companyId: company!.id, profileId: gateway!.profileId!, targetType: "agent", targetId: gatewayReader!.id,
});
await db.insert(toolConnectionInstalls).values({
companyId: company!.id, connectionId: connection!.id, targetType: "agent", targetId: gatewayReader!.id,
});
const effective = await toolAccessService(db).getEffectiveProfilesForAgent(company!.id, gatewayReader!.id);
expect(effective.allowedTools.map((tool) => tool.id).sort()).toEqual(allowed.map((tool) => tool.id).sort());
expect(effective.allowedToolNames).not.toContain("excluded");
expect(effective.allowedToolNames).not.toContain("unassigned");
expect(effective.allowedToolNames).not.toContain("new_after_snapshot");
const reused = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: randomUUID() });
expect(reused[0]!.connectionId).toBe(servers[0]!.connectionId);
expect(await db.select().from(toolMcpGateways)).toHaveLength(1);
});
it("exposes only the dedicated GitHub connection when a personal connection is also installed", async () => {
process.env.PAPERCLIP_API_URL = "https://paperclip.example.test";
const [company] = await db.insert(companies).values({
name: `Runtime GitHub identity ${randomUUID()}`,
issuePrefix: `RG${randomUUID().slice(0, 5).toUpperCase()}`,
}).returning();
await db.insert(companyMemberships).values({
companyId: company!.id,
principalType: "user",
principalId: "responsible-user",
status: "active",
membershipRole: "member",
});
const [agent] = await db.insert(agents).values({
companyId: company!.id,
name: "Dedicated GitHub Agent",
role: "engineer",
adapterType: "codex_local",
adapterConfig: {},
}).returning();
const [application] = await db.insert(toolApplications).values({
companyId: company!.id,
applicationKey: `github-${randomUUID().slice(0, 8)}`,
name: "GitHub",
type: "mcp_http",
status: "active",
metadata: { sourceTemplateKey: "github" },
}).returning();
const [personal, dedicated] = await db.insert(toolConnections).values([
{
companyId: company!.id,
applicationId: application!.id,
name: "Responsible user's GitHub",
uid: `github/${randomUUID()}`,
transport: "mcp_remote",
credentialPolicy: "per_user",
status: "active",
enabled: true,
healthStatus: "ok",
config: {},
transportConfig: { sourceTemplateKey: "github" },
},
{
companyId: company!.id,
applicationId: application!.id,
name: "Dedicated GitHub",
uid: `github/${randomUUID()}`,
transport: "mcp_remote",
credentialPolicy: "per_agent",
status: "active",
enabled: true,
healthStatus: "ok",
config: {},
transportConfig: { sourceTemplateKey: "github" },
},
]).returning();
await db.insert(connectionGrants).values([
{
companyId: company!.id,
connectionId: personal!.id,
kind: "user",
subjectUserId: "responsible-user",
status: "active",
isDefault: false,
},
{
companyId: company!.id,
connectionId: dedicated!.id,
kind: "agent",
subjectAgentId: agent!.id,
status: "active",
isDefault: false,
},
]);
await db.insert(toolConnectionInstalls).values([
{
companyId: company!.id,
connectionId: personal!.id,
targetType: "company",
targetId: company!.id,
},
{
companyId: company!.id,
connectionId: dedicated!.id,
targetType: "agent",
targetId: agent!.id,
},
]);
const [profile] = await db.insert(toolProfiles).values({
companyId: company!.id,
profileKey: `github-identities:${agent!.id}`,
name: "GitHub identities",
defaultAction: "deny",
}).returning();
await db.insert(toolProfileEntries).values([personal!, dedicated!].map((connection) => ({
companyId: company!.id,
profileId: profile!.id,
selectorType: "connection" as const,
effect: "include" as const,
applicationId: application!.id,
connectionId: connection.id,
})));
await db.insert(toolProfileBindings).values({
companyId: company!.id,
profileId: profile!.id,
targetType: "agent",
targetId: agent!.id,
});
const [run] = await db.insert(heartbeatRuns).values({
companyId: company!.id,
agentId: agent!.id,
status: "running",
responsibleUserId: "responsible-user",
contextSnapshot: {},
}).returning();
const servers = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId: run!.id });
expect(servers).toHaveLength(1);
const [runtimeGateway] = await db.select().from(toolMcpGateways);
expect(runtimeGateway).toBeTruthy();
const runtimeEntries = await db.select().from(toolProfileEntries)
.where(eq(toolProfileEntries.profileId, runtimeGateway!.profileId!));
expect(runtimeEntries.map((entry) => entry.connectionId)).toEqual([dedicated!.id]);
});
it("audits permitted remote MCP connections that were not installed when delivery is empty", async () => {
const [company] = await db.insert(companies).values({
name: `Runtime MCP diagnostic ${randomUUID()}`,
issuePrefix: `RD${randomUUID().slice(0, 5).toUpperCase()}`,
}).returning();
const [agent] = await db.insert(agents).values({
companyId: company!.id,
name: "Runtime MCP Diagnostic Agent",
role: "engineer",
adapterType: "codex_local",
adapterConfig: {},
}).returning();
const [application] = await db.insert(toolApplications).values({
companyId: company!.id,
applicationKey: `runtime-diagnostic-${randomUUID().slice(0, 8)}`,
name: "Zapier",
type: "mcp_http",
status: "active",
}).returning();
const [connection] = await db.insert(toolConnections).values({
companyId: company!.id,
applicationId: application!.id,
name: "Zapier",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
config: { url: "https://zapier.example.test/mcp" },
}).returning();
const [profile] = await db.insert(toolProfiles).values({
companyId: company!.id,
profileKey: `app:${connection!.id}`,
name: "Zapier",
defaultAction: "deny",
}).returning();
await db.insert(toolProfileEntries).values({
companyId: company!.id,
profileId: profile!.id,
selectorType: "connection",
effect: "include",
applicationId: application!.id,
connectionId: connection!.id,
});
await db.insert(toolProfileBindings).values({
companyId: company!.id,
profileId: profile!.id,
targetType: "agent",
targetId: agent!.id,
});
const runId = randomUUID();
await db.insert(heartbeatRuns).values({
id: runId,
companyId: company!.id,
agentId: agent!.id,
status: "running",
contextSnapshot: {},
});
const servers = await buildPaperclipRuntimeMcpServers({ db, agent: agent!, runId });
expect(servers).toEqual([]);
const [activity] = await db
.select()
.from(activityLog)
.where(eq(activityLog.action, "tool_gateway.runtime_mcp_delivery"));
expect(activity).toMatchObject({
companyId: company!.id,
agentId: agent!.id,
runId,
details: expect.objectContaining({
reasonCode: "permitted_connections_not_installed",
deliveredServerCount: 0,
permittedNotInstalledCount: 1,
permittedNotInstalledConnections: [{ id: connection!.id, name: "Zapier" }],
}),
});
const [audit] = await db.select().from(toolAccessAuditEvents);
expect(audit).toMatchObject({
companyId: company!.id,
actorType: "agent",
actorId: agent!.id,
reasonCode: "permitted_connections_not_installed",
details: expect.objectContaining({ runId, deliveredServerCount: 0 }),
});
});
it("injects only managed gateways whose profile connections are installed for the agent", async () => {
const [company] = await db.insert(companies).values({
name: `Managed gateway installs ${randomUUID()}`,
issuePrefix: `MG${randomUUID().slice(0, 5).toUpperCase()}`,
}).returning();
const [agent] = await db.insert(agents).values({
companyId: company!.id,
name: "Managed Gateway Agent",
role: "engineer",
adapterType: "codex_local",
adapterConfig: {},
}).returning();
const [application] = await db.insert(toolApplications).values({
companyId: company!.id,
applicationKey: `managed-gateway-${randomUUID().slice(0, 8)}`,
name: "Managed Gateway App",
type: "mcp_http",
status: "active",
}).returning();
const connections = await db.insert(toolConnections).values([
{
companyId: company!.id,
applicationId: application!.id,
name: "Installed gateway connection",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
},
{
companyId: company!.id,
applicationId: application!.id,
name: "Uninstalled gateway connection",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
},
]).returning();
const profiles = await db.insert(toolProfiles).values(connections.map((connection) => ({
companyId: company!.id,
profileKey: `gateway:${connection.id}`,
name: connection.name,
defaultAction: "deny" as const,
}))).returning();
await db.insert(toolProfileEntries).values(profiles.map((profile, index) => ({
companyId: company!.id,
profileId: profile.id,
selectorType: "connection" as const,
effect: "include" as const,
connectionId: connections[index]!.id,
})));
const gateways = await db.insert(toolMcpGateways).values(profiles.map((profile, index) => ({
companyId: company!.id,
name: `${connections[index]!.name} gateway`,
slug: `gateway-${index}-${randomUUID().slice(0, 8)}`,
profileId: profile.id,
status: "active" as const,
}))).returning();
await db.insert(toolConnectionInstalls).values({
companyId: company!.id,
connectionId: connections[0]!.id,
targetType: "agent",
targetId: agent!.id,
});
const config = await createManagedMcpRunConfig({
db,
agent: agent!,
runId: randomUUID(),
config: {},
projectId: null,
issueId: null,
});
expect(config?.gateways).toHaveLength(1);
expect(config?.gateways[0]).toMatchObject({
id: gateways[0]!.id,
name: gateways[0]!.name,
endpointPath: `/mcp/gateways/${gateways[0]!.gatewayPublicId}`,
});
expect(config?.gateways.some((gateway) => gateway.id === gateways[1]!.id)).toBe(false);
});
});