feat(connections): add experimental memory providers and remote MCP access (#13942)

## Thinking Path

> - Paperclip manages AI agents and their work.
> - Connections give agents governed access to external tools.
> - Agents need durable memory across tasks and execution environments.
> - Mem0, Zep, Supermemory, Cognee, and Honcho provide hosted memory
tools.
> - This pull request adds their setup flows behind an experimental
toggle.
> - It also delivers assigned MCP tools through the native remote Codex
runner.
> - Operators can connect a provider once and use the same governed
tools locally or in Daytona.

## Linked Issues or Issue Description

**Problem or motivation**

The Apps catalog lacks a complete set of memory providers. Remote native
Codex agents also need access to assigned managed MCP tools without
receiving provider credentials.

**Proposed solution**

Add five memory connectors behind the disabled-by-default Experimental
memory connectors setting. Use the existing connection setup and
permissions UI. Default their tools to Allowed. Preserve company
boundaries, operator permission changes, provider scopes, and audit
attribution.

**Alternatives considered**

Direct provider credentials in each sandbox would duplicate setup and
bypass the managed gateway. The remote runner instead uses its existing
protocol channel to call the gateway on the server.

**Roadmap alignment**

This maintainer-requested experiment supports the Memory / Knowledge and
Connected Apps roadmap areas. It adds provider connections without
introducing a separate memory UI. Related connector authoring
documentation is tracked in #13692; no duplicate memory-provider
implementation was found.

## What Changed

- Add provider definitions, official branding, and the experimental
setting for all five providers.
- Use OAuth for Zep and Supermemory, API credentials for Mem0 and
Honcho, and a bundled Cloud API bridge for Cognee with no runtime
downloads or subprocesses.
- Default memory tools to Allowed and classify destructive actions
explicitly.
- Fix personal remote credential resolution and propagate provider tool
errors.
- Relay assigned managed MCP tools to remote native Codex through the
runner protocol. Recheck current authority for each call and rotate
stale tool contracts.
- Add 21 Storybook states and complete OAuth walkthrough fixtures.
- Document provider research, sanitized tool inventory, and live local
and Daytona proof.

## Verification

- Passed workspace typecheck: `pnpm -r typecheck`.
- Passed production build: `pnpm build`.
- Full local `pnpm test:run`: 13,273 passed, with failures from
process/readiness timeouts under parallel load. Reran all 16 affected
suites with one worker: 456 passed, leaving two macOS `/var` versus
`/private/var` path assertions. Both passed with `TMPDIR=/private/tmp`.
No test failures remain unverified. Latest-head remote CI passes all 54
checks (two optional Storybook jobs skipped). Greptile is 5/5 with no
unresolved findings.
- Latest Cognee gateway regression: 71 passed, including public
deployment without a runtime host and immediate recovery after a
provider error. Bundled bridge tests: 25 passed.
- Browser setup and real agent tasks exercised all five providers. Mem0,
Cognee, Zep, and Honcho have successful store/retrieve proof.
- Supermemory now has scoped read/write consent. Local storage and real
Daytona write, document read, and semantic recall passed; indexing
completion was verified before claiming success.
- All five providers were exercised through a real Daytona sandbox and
its native runner MCP relay. Provider credentials remained on the
server. The final bundled Cognee bridge also passed a fresh Daytona
store/recall run. All disposable sandboxes were removed and verified
absent after testing.
- Storybook is rebuilt and contains the experimental toggle, catalog,
setup, permissions, and error states. The Zep and Supermemory access
steps advance correctly.

## Risks

- Provider OAuth scopes and plan limits remain independent of Paperclip
tool permissions. An Allowed tool can still be rejected by the provider.
- Providers can queue memory indexing; save acceptance does not prove
that semantic recall is ready.
- Remote tool contracts must stay synchronized with current connection
authority. Regression tests cover revocation and stale contracts.
- This change has no database migration. Existing connections remain
usable when the experimental catalog toggle is disabled.

## Model Used

OpenAI Codex, GPT-6 Astra (`gpt-6-astra`), with reasoning, repository
edits, code execution, and browser automation. The exact context window
size is not exposed in this session. Live acceptance agents used
`gpt-5.6-sol`.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-24 15:54:38 -05:00
1 parent e006c18f20
commit 18dac1e1ef
54 files changed
+3066 -135

No files matched your search

@@ -44,6 +44,7 @@ describe("instance settings service", () => {
enableAgentChat: false,
enableChatConnectors: false,
enableMcpAggregators: false,
enableMemoryConnectors: false,
enableConferenceRoomChat: false,
enableClassicTaskInterface: false,
enableExternalObjects: false,
@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from "vitest";
import { classifyRisk } from "../services/tool-access.js";
import { COGNEE_STDIO_TEMPLATE, cogneeCloudUrl, callCogneeCloud } from "../services/cognee-connection.js";
describe("memory tool governance", () => {
it.each([
["mem0", "add_memory", "write"], ["mem0", "search_memories", "read"],
["mem0", "delete_entities", "destructive"], ["zep", "add_memory_to_graph", "write"],
["supermemory", "add_memory", "destructive"], ["supermemory", "select-space", "write"],
["supermemory", "get_profile", "read"], ["cognee", "remember", "write"],
["cognee", "recall", "read"], ["cognee", "forget", "destructive"],
["honcho", "create_peer", "write"], ["honcho", "future_unknown_action", "write"],
])("classifies %s %s even with a misleading read hint", (provider, name, expected) => {
expect(classifyRisk({ name, annotations: { readOnlyHint: true } }, provider)).toBe(expected);
});
it("keeps the approved Cognee bridge free of runtime package resolution", () => {
expect(COGNEE_STDIO_TEMPLATE.command).toBeNull();
expect(COGNEE_STDIO_TEMPLATE.args).toEqual([]);
expect(COGNEE_STDIO_TEMPLATE.envKeys).toEqual(["COGNEE_BASE_URL", "COGNEE_API_KEY"]);
expect(COGNEE_STDIO_TEMPLATE.tools.map(t => t.name)).toEqual(["remember", "recall", "forget"]);
});
it.each(["http://localhost", "https://evil.test", "https://tenant.aws.cognee.ai@evil.test", "https://tenant.aws.cognee.ai/other", "https://tenant.aws.cognee.ai?key=secret", "https://tenant.aws.cognee.ai:8443"])("rejects unreviewed Cognee URL %s", (url) => {
expect(() => cogneeCloudUrl(url)).toThrow();
});
it("accepts the tenant API origin", () => expect(cogneeCloudUrl("https://tenant.aws.cognee.ai").origin).toBe("https://tenant.aws.cognee.ai"));
it("writes text as a file to the tenant-only Cloud endpoint", async () => {
const request = vi.fn().mockResolvedValue({ status: "completed" });
const result = await callCogneeCloud({ baseUrl: "https://fixture.aws.cognee.ai", apiKey: "fixture-key",
tool: "remember", parameters: { data: "synthetic memory", dataset_name: "fixture" }, request,
signal: AbortSignal.timeout(1000) });
const [url, init] = request.mock.calls[0]!;
expect(url.href).toBe("https://fixture.aws.cognee.ai/api/v1/remember");
expect(init).toMatchObject({ method: "POST", redirect: "manual", headers: expect.objectContaining({ "x-api-key": "fixture-key" }) });
expect(Buffer.isBuffer(init.body)).toBe(true);
const form = await new Response(init.body, { headers: init.headers }).formData();
expect(form.get("datasetName")).toBe("fixture");
expect(await (form.get("data") as File).text()).toBe("synthetic memory");
expect(result).toMatchObject({ isError: false, structuredContent: { result: { status: "completed" } } });
});
it("keeps session writes on the Cloud session endpoint", async () => {
const request = vi.fn().mockResolvedValue({ status: "completed" });
await callCogneeCloud({ baseUrl: "https://fixture.aws.cognee.ai", apiKey: "key", tool: "remember",
parameters: { data: "text", session_id: "session", dataset_name: "fixture" }, request, signal: AbortSignal.timeout(1000) });
expect(request.mock.calls[0]![0].pathname).toBe("/api/v1/remember/entry");
expect(JSON.parse(request.mock.calls[0]![1].body)).toMatchObject({
entry: { type: "qa", answer: "text" }, session_id: "session", dataset_name: "fixture" });
});
it("preserves scoped recall arguments and does not fetch other datasets", async () => {
const request = vi.fn().mockResolvedValue(["memory"]);
await callCogneeCloud({ baseUrl: "https://fixture.aws.cognee.ai", apiKey: "key", tool: "recall",
parameters: { query: "find", datasets: "one, two", search_type: "chunks", top_k: 3 }, request, signal: AbortSignal.timeout(1000) });
expect(request).toHaveBeenCalledTimes(1);
expect(request.mock.calls[0]![0].pathname).toBe("/api/v1/recall");
expect(JSON.parse(request.mock.calls[0]![1].body)).toEqual({ query: "find", datasets: ["one", "two"], search_type: "CHUNKS", top_k: 3 });
});
it("matches the official client's unscoped dataset discovery", async () => {
const request = vi.fn().mockResolvedValueOnce([{ name: "one" }]).mockResolvedValueOnce(["memory"]);
await callCogneeCloud({ baseUrl: "https://fixture.aws.cognee.ai", apiKey: "key", tool: "recall",
parameters: { query: "find" }, request, signal: AbortSignal.timeout(1000) });
expect(request.mock.calls[0]![0].pathname).toBe("/api/v1/datasets/");
expect(JSON.parse(request.mock.calls[1]![1].body).datasets).toEqual(["one"]);
});
it("requires an explicit delete target and never falls back after a provider failure", async () => {
const request = vi.fn().mockRejectedValue(new Error("Cloud unavailable"));
const input = { baseUrl: "https://fixture.aws.cognee.ai", apiKey: "key", tool: "forget", parameters: {}, request, signal: AbortSignal.timeout(1000) };
await expect(callCogneeCloud(input)).rejects.toThrow("Specify a dataset");
expect(request).not.toHaveBeenCalled();
await expect(callCogneeCloud({ ...input, parameters: { dataset: "fixture" } })).rejects.toThrow("Cloud unavailable");
expect(request).toHaveBeenCalledTimes(1);
expect(JSON.parse(request.mock.calls[0]![1].body)).toEqual({ dataset: "fixture", everything: false });
});
});
@@ -811,14 +811,14 @@ describeEmbeddedPostgres("tool access service", () => {
process.env.PAPERCLIP_TOOL_ACCESS_TEST_DATABASE_URL?.trim();
if (externalDatabaseUrl) {
db = createDb(externalDatabaseUrl);
await instanceSettingsService(db).updateExperimental({ enableMcpAggregators: true });
await instanceSettingsService(db).updateExperimental({ enableMcpAggregators: true, enableMemoryConnectors: true });
return;
}
tempDb = await startEmbeddedPostgresTestDatabase(
"paperclip-tool-access-service-",
);
db = createDb(tempDb.connectionString);
await instanceSettingsService(db).updateExperimental({ enableMcpAggregators: true });
await instanceSettingsService(db).updateExperimental({ enableMcpAggregators: true, enableMemoryConnectors: true });
}, 20_000);
afterEach(async () => {
@@ -5092,7 +5092,7 @@ describeEmbeddedPostgres("tool access service", () => {
"youcom",
]),
);
expect(res.body.apps).toHaveLength(52);
expect(res.body.apps).toHaveLength(56);
expect(
res.body.apps.find((app: { slug: string }) => app.slug === "gmail")
.ownershipAvailability,
@@ -11589,6 +11589,149 @@ describeEmbeddedPostgres("tool access service", () => {
);
});
it.each(["mem0", "zep", "supermemory", "cognee", "honcho"])("rejects %s setup before creating credentials when memory connectors are disabled", async (provider) => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
await instanceSettingsService(db).updateExperimental({ enableMemoryConnectors: false });
try {
const response = await request(createRouteApp(db)).get(`/api/companies/${company.id}/tools/gallery`).expect(200);
expect(response.body.apps.some((app: { slug: string }) => app.slug === provider)).toBe(false);
await expect(service.connectGalleryApp(company.id, { galleryKey: provider })).rejects.toMatchObject({ status: 403, details: { code: "memory_connectors_disabled" } });
expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toHaveLength(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.companyId, company.id))).toHaveLength(0);
} finally {
await instanceSettingsService(db).updateExperimental({ enableMemoryConnectors: true });
}
});
it("rotates an existing Mem0 key while new memory setup is disabled", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
mockToolsList([{ name: "search_memories", annotations: { readOnlyHint: true } }]);
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "mem0", credentialValues: { "credentials.authorization": "old-key" },
});
await db.update(toolConnections).set({ status: "active" }).where(eq(toolConnections.id, connected.connectionId));
await instanceSettingsService(db).updateExperimental({ enableMemoryConnectors: false });
try {
const result = await service.reconnectGalleryApp(connected.connectionId, company.id,
{ credentialValues: { "credentials.authorization": "new-key" } });
expect(result.connection.id).toBe(connected.connectionId);
expect(result.connection.healthStatus).toBe("ok");
} finally {
await instanceSettingsService(db).updateExperimental({ enableMemoryConnectors: true });
}
});
it("keeps active Cognee tools available during a transient Cloud probe outage", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("[]", { status: 200 }));
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "cognee", credentialValues: { "env.COGNEE_BASE_URL": "https://fixture.aws.cognee.ai", "env.COGNEE_API_KEY": "key" },
});
await db.update(toolConnections).set({ status: "active" }).where(eq(toolConnections.id, connected.connectionId));
fetchMock.mockReset().mockRejectedValue(new Error("temporary timeout"));
const result = await service.checkHealth(connected.connectionId);
expect(result.connection.healthStatus).toBe("ok");
expect(fetchMock).not.toHaveBeenCalled();
const catalog = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, connected.connectionId));
expect(catalog).toHaveLength(3);
});
it("creates a user-owned value when reconnect restores a missing personal credential field", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
mockToolsList([{ name: "search_memories", annotations: { readOnlyHint: true } }]);
const actor = { actorType: "user" as const, actorId: "personal-reconnect-owner" };
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "mem0", grantKind: "user", credentialValues: { "credentials.authorization": "old-key" },
}, actor);
const { grants } = await service.listConnectionGrants(connected.connectionId, company.id);
await db.update(connectionGrants).set({ credentialSecretRefs: [] }).where(eq(connectionGrants.id, grants[0]!.id));
await service.reconnectGalleryApp(connected.connectionId, company.id,
{ credentialValues: { "credentials.authorization": "restored-key" } }, actor);
const after = await service.listConnectionGrants(connected.connectionId, company.id);
const ref = after.grants[0]!.credentialSecretRefs[0]!;
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.id, ref.secretId));
expect(secret).toMatchObject({ scope: "user", ownerUserId: actor.actorId });
const resolved = await secretService(db).resolveUserSecretValue(company.id, {
definitionId: secret.userSecretDefinitionId!, responsibleUserId: actor.actorId,
}, { consumerType: "tool_connection", consumerId: connected.connectionId, configPath: ref.configPath,
actorType: "system", actorId: null, responsibleUserId: actor.actorId });
expect(resolved?.value).toBe("restored-key");
expect((await service.getConnection(connected.connectionId, company.id)).credentialSecretRefs).toEqual([]);
});
it("keeps rejected Mem0 API keys on the key-entry path rather than switching to OAuth", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("unauthorized", { status: 401, headers: { "www-authenticate": "Bearer" } }));
await expect(service.connectGalleryApp(company.id, {
galleryKey: "mem0", credentialValues: { "credentials.authorization": "invalid-key" },
})).rejects.toMatchObject({ status: 422, details: { code: "memory_api_key_rejected" } });
expect(await db.select().from(companySecrets).where(eq(companySecrets.companyId, company.id))).toHaveLength(0);
});
it("vaults Cognee environment credentials and verifies Cloud access before exposing its reviewed tools", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("[]", { status: 200 }));
const key = "cognee-private-fixture-key";
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "cognee",
credentialValues: { "env.COGNEE_BASE_URL": "https://fixture.aws.cognee.ai", "env.COGNEE_API_KEY": key },
});
expect(fetchMock).toHaveBeenCalledWith("https://fixture.aws.cognee.ai/api/v1/datasets/", expect.objectContaining({
method: "GET", headers: { "X-Api-Key": key }, redirect: "manual",
}));
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
expect(connection.config).toMatchObject({ templateId: "paperclip.cognee-cloud" });
expect(connection.credentialSecretRefs.map(ref => ref.configPath).sort()).toEqual(["env.COGNEE_API_KEY", "env.COGNEE_BASE_URL"]);
expect(JSON.stringify(connected)).not.toContain(key);
expect(JSON.stringify(connection)).not.toContain(key);
const catalog = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, connected.connectionId));
expect(catalog.map(entry => [entry.toolName, entry.riskLevel]).sort()).toEqual([["forget", "destructive"], ["recall", "read"], ["remember", "write"]]);
});
it("resolves personal Cognee credentials through their owner and durable declarations", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("[]", { status: 200 }));
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "cognee", grantKind: "user",
credentialValues: { "env.COGNEE_BASE_URL": "https://fixture.aws.cognee.ai", "env.COGNEE_API_KEY": "personal-cognee-key" },
}, { actorType: "user", actorId: "carol" });
const { grants } = await service.listConnectionGrants(connected.connectionId, company.id);
expect(grants).toHaveLength(1);
expect(connected.connection.credentialSecretRefs).toEqual([]);
const vault = secretService(db);
for (const ref of grants[0]!.credentialSecretRefs) {
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.id, ref.secretId));
expect(secret).toMatchObject({ scope: "user", ownerUserId: "carol" });
const resolved = await vault.resolveUserSecretValue(company.id, {
definitionId: secret.userSecretDefinitionId, responsibleUserId: "carol",
}, { consumerType: "tool_connection", consumerId: connected.connectionId, configPath: ref.configPath,
actorType: "system", actorId: null, responsibleUserId: "carol" });
expect(resolved?.value).toBe(ref.configPath === "env.COGNEE_API_KEY" ? "personal-cognee-key" : "https://fixture.aws.cognee.ai");
await expect(vault.resolveUserSecretValue(company.id, {
definitionId: secret.userSecretDefinitionId, responsibleUserId: "another-user",
})).rejects.toMatchObject({ status: 422, details: { code: "user_secret_missing" } });
}
});
it.each(["organization", "user"] as const)("cleans up a rejected %s Cognee connection and its vault records", async (grantKind) => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("unauthorized", { status: 401 }));
await expect(service.connectGalleryApp(company.id, {
galleryKey: "cognee", grantKind, credentialValues: { "env.COGNEE_BASE_URL": "https://fixture.aws.cognee.ai", "env.COGNEE_API_KEY": "invalid-key" },
}, { actorType: "user", actorId: "carol" })).rejects.toMatchObject({ status: 422, details: { code: "cognee_access_unverified" } });
expect(await db.select().from(userSecretDefinitions).where(eq(userSecretDefinitions.companyId, company.id))).toHaveLength(0);
expect(await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.companyId, company.id))).toHaveLength(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.companyId, company.id))).toHaveLength(0);
});
it("retains an encrypted API key when the same draft method resumes", async () => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
@@ -1439,16 +1439,14 @@ describeEmbeddedPostgres("tool gateway service", () => {
const tool = (await gateway.listToolsForSession(session.token))
.find((candidate) => candidate.providerType === "mcp_remote_http");
const result = await gateway.executeTool({
await expect(gateway.executeTool({
sessionToken: session.token,
tool: tool!.name,
parameters: {},
})).rejects.toMatchObject({
reasonCode: "tool_error",
message: expect.stringContaining("enroll the signed-in Workspace account and this OAuth client's Google Cloud project"),
});
expect(result.status).toBe("completed");
expect((result.result as { content?: string }).content).toContain(
"enroll the signed-in Workspace account and this OAuth client's Google Cloud project",
);
});
it("injects Vercel tokens at dispatch and refreshes exactly once after an upstream 401", async () => {
+152
View File
@@ -54,6 +54,7 @@ import {
} from "../services/tool-content-guards.js";
import { createToolGatewayService, ToolGatewayHttpError } from "../services/tool-gateway.js";
import { secretService } from "../services/secrets.js";
import * as cogneeBridge from "../services/cognee-connection.js";
import { createKvDemoHttpServer, type KvDemoHttpServer } from "../../../packages/kv-demo-mcp-server/src/http.js";
import {
getEmbeddedPostgresTestSupport,
@@ -582,6 +583,72 @@ describeEmbeddedPostgres("tool gateway acceptance", () => {
await tempDb?.cleanup();
});
it("preserves provider tool errors in MCP responses and failed invocation audits", async () => {
const company = await createCompany(db);
const remote = await startFakeRemoteMcpServer(({ body }) => ({
body: {
jsonrpc: "2.0",
id: body?.id,
result: { content: [{ type: "text", text: "Search denied: outside consented tag" }], isError: true },
},
}));
try {
const { application, connection, catalogEntry } = await createRemoteMcpTool(db, company.id, {
url: remote.url, toolName: "search_memory", riskLevel: "read",
});
await db.update(toolCatalogEntries).set({
inputSchema: { type: "object", properties: {}, additionalProperties: false },
}).where(eq(toolCatalogEntries.id, catalogEntry.id));
const toolName = expectedConnectedToolName({
applicationKey: application.applicationKey,
connectionId: connection.id,
toolName: catalogEntry.toolName,
});
const [profile] = await db.insert(toolProfiles).values({
companyId: company.id, profileKey: `error-${randomUUID()}`,
name: "Provider error test", defaultAction: "deny",
}).returning();
await db.insert(toolProfileEntries).values({
companyId: company.id, profileId: profile.id,
selectorType: "tool_name", effect: "include", toolName,
});
const gateway = createTestToolGatewayService(db);
const named = await gateway.createNamedGateway({
companyId: company.id, body: { name: "Provider error test", profileId: profile.id },
});
const token = await gateway.createNamedGatewayToken({
companyId: company.id, gatewayId: named.id, body: { name: "Test" },
});
const response = await request(createGatewayRouteApp(db, gateway))
.post(named.endpointPath)
.set("authorization", `Bearer ${token.token}`)
.send({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: toolName, arguments: {} } })
.expect(200);
expect(response.body.result).toEqual({
content: [{ type: "text", text: "Search denied: outside consented tag" }], isError: true,
});
expect(await db.select().from(toolInvocations).where(eq(toolInvocations.companyId, company.id)))
.toEqual([expect.objectContaining({ status: "failed", errorCode: "tool_error" })]);
const events = await db.select().from(toolCallEvents).where(eq(toolCallEvents.companyId, company.id));
expect(events).toContainEqual(expect.objectContaining({ eventType: "call_failed", outcome: "failure", reasonCode: "tool_error" }));
expect(events.some((event) => event.eventType === "call_completed")).toBe(false);
const agent = await createAgent(db, company.id);
await allowAllToolsForAgent(db, company.id, agent.id);
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user",
principalId: "test-user", status: "active", membershipRole: "member" });
const testCall = await gateway.executeTestCall({ companyId: company.id, connectionId: connection.id,
agentId: agent.id, userId: "test-user", toolName, parameters: {} });
expect(testCall).toMatchObject({ decision: "allowed", error: { reasonCode: "tool_error" } });
expect(await db.select().from(toolInvocations).where(eq(toolInvocations.id, testCall.invocationId)))
.toEqual([expect.objectContaining({ status: "failed", errorCode: "tool_error" })]);
const testEvents = await db.select().from(toolCallEvents).where(eq(toolCallEvents.invocationId, testCall.invocationId));
expect(testEvents.some(event => event.eventType === "call_failed")).toBe(true);
expect(testEvents.some(event => event.eventType === "call_completed")).toBe(false);
} finally {
await remote.close();
}
});
it("exposes a named gateway with scoped bearer-token auth and revocation", async () => {
const company = await createCompany(db);
const remote = await startFakeRemoteMcpServer(async ({ body }) => ({
@@ -1659,6 +1726,54 @@ rl.on("line", (line) => {
}
});
it.each(["credentials.authorization", "headers.X-Api-Key", "oauth.access_token"])(
"resolves a personal remote credential using its declared %s path",
async (configPath) => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { run } = await createIssueAndRun(db, company.id, agent.id);
await createActiveMember(db, company.id, "alice");
await db.update(heartbeatRuns).set({ responsibleUserId: "alice" }).where(eq(heartbeatRuns.id, run.id));
const secrets = secretService(db);
const definition = await secrets.createUserSecretDefinition(company.id, {
name: "Personal remote token",
key: `personal_remote_${randomUUID().replace(/-/g, "")}`,
provider: "local_encrypted",
});
const secret = await secrets.createCurrentUserSecretValue(company.id, "alice", {
definitionId: definition.id, value: "personal-remote-test-token",
});
const remote = await createRemoteMcpTool(db, company.id);
await db.update(toolConnections).set({
credentialPolicy: "per_user",
credentialRefs: [{ name: configPath, secretId: secret.id, placement: "header", key: "Authorization", prefix: "Bearer " }],
}).where(eq(toolConnections.id, remote.connection.id));
await secrets.syncUserSecretDeclarationsForTarget(company.id,
{ targetType: "tool_connection", targetId: remote.connection.id },
[{ definitionKey: definition.key, configPath, envKey: "Authorization", versionSelector: "latest", required: true }],
{ replaceAll: true });
await db.insert(connectionGrants).values({
companyId: company.id, connectionId: remote.connection.id, kind: "user", subjectUserId: "alice",
credentialSecretRefs: [{ secretId: secret.id, configPath, versionSelector: "latest" }],
status: "active", isDefault: false,
});
await allowAllToolsForAgent(db, company.id, agent.id);
const headers: string[] = [];
const gateway = createTestToolGatewayService(db, { remoteHttpRequest: async (_url, init) => {
headers.push(new Headers(init.headers).get("authorization") ?? "");
const body = JSON.parse(String(init.body)) as { id: string };
return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id,
result: { content: [{ type: "text", text: "retrieved synthetic memory" }] } }),
{ headers: { "content-type": "application/json" } });
} });
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const tool = (await gateway.listToolsForSession(session.token)).find(t => t.connectionId === remote.connection.id)!;
expect((await gateway.executeTool({ sessionToken: session.token, tool: tool.name,
parameters: { key: "test", value: "synthetic" } })).status).toBe("completed");
expect(headers).toEqual(["Bearer personal-remote-test-token"]);
},
);
it("passes only the selected grant identity to local stdio MCP processes", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
@@ -5089,6 +5204,43 @@ rl.on("line", (line) => {
});
});
it("calls bundled Cognee in public mode and recovers from provider errors without runtime backoff", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { run } = await createIssueAndRun(db, company.id, agent.id);
const refs = await Promise.all(Object.entries({
COGNEE_BASE_URL: "https://fixture.aws.cognee.ai",
COGNEE_API_KEY: "fixture-key",
}).map(async ([key, value]) => {
const secret = await secretService(db).create(company.id, {
name: key, key: `${key}_${randomUUID().replace(/-/g, "")}`,
provider: "local_encrypted", value,
});
return { secretId: secret.id, versionSelector: "latest", configPath: `env.${key}`, required: true };
}));
const local = await createLocalStdioMcpTool(db, company.id, {
applicationKey: "cognee", toolName: "recall",
connectionConfig: { templateId: "paperclip.cognee-cloud" }, credentialSecretRefs: refs,
});
await allowAllToolsForAgent(db, company.id, agent.id);
const bridge = vi.spyOn(cogneeBridge, "callCogneeCloud")
.mockRejectedValueOnce(new Error("Cloud temporarily unavailable"))
.mockResolvedValue({ content: [{ type: "text", text: "recalled synthetic memory" }],
structuredContent: { result: "recalled synthetic memory" }, isError: false });
const gateway = createTestToolGatewayService(db, {
deploymentMode: "authenticated", deploymentExposure: "public", trustedLocalStdioRuntimeHost: null,
});
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const tool = (await gateway.listToolsForSession(session.token)).find(t => t.connectionId === local.connection.id)!;
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name,
parameters: { message: "synthetic" } })).rejects.toThrow("Cloud temporarily unavailable");
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name,
parameters: { message: "synthetic" } })).resolves.toMatchObject({ status: "completed" });
expect(bridge).toHaveBeenCalledTimes(2);
expect(await db.select().from(toolRuntimeSlots).where(eq(toolRuntimeSlots.connectionId, local.connection.id))).toHaveLength(0);
bridge.mockRestore();
});
it("fails closed for hosted public local stdio unless a trusted runtime host is configured", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
+2
View File
@@ -5,6 +5,7 @@ import { projectToolRoutes } from "./routes/project-tools.js";
import { emailChannelService } from "./services/email-channels.js";
import { emailRoutes, emailWebhookRoutes } from "./routes/email.js";
import { toolActionDeliveryService } from "./services/tool-action-delivery.js";
import { registerAssignedMcpGateway } from "./services/native-runtime/assigned-mcp-tools.js";
import express, { Router, type Request as ExpressRequest } from "express";
import {
createServer as createHttpServer,
@@ -843,6 +844,7 @@ export async function createApp(
}));
api.use(slackToolRoutes(db, opts.authPublicBaseUrl));
app.locals.toolGateway = toolGateway;
registerAssignedMcpGateway(db, toolGateway);
app.locals.toolActionDeliveries = toolActionDeliveries;
app.use(mcpGatewayProtocolRoutes(toolGateway));
api.use(aiConnectionRoutes(db, { deploymentMode: opts.deploymentMode, deploymentExposure: opts.deploymentExposure, trustedLocalStdioRuntimeHost }));
+3 -2
View File
@@ -5,6 +5,7 @@ import { and, eq, or } from "drizzle-orm";
import {
APP_STORE_DEFINITIONS,
isRemoteMcpConnectorId,
isMemoryConnectorId,
GITHUB_CONNECTOR_PROFILES,
GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
isAgentStatusAssignableToWork,
@@ -815,7 +816,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
? await options.paperclipCloudConnector.getCapabilities()
: [];
const vercelConnect = vercelConnectIntegrationStatus();
const { enableMcpAggregators } = await instanceSettingsService(db).getExperimental();
const { enableMcpAggregators, enableMemoryConnectors } = await instanceSettingsService(db).getExperimental();
res.json({
capabilities: await describeConnectionCreateCapabilities(req, companyId),
credentialSources: {
@@ -831,7 +832,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
: "Vercel Connect setup is disabled on this Paperclip instance.",
},
},
apps: APP_STORE_DEFINITIONS.filter((app) => enableMcpAggregators || !isRemoteMcpConnectorId(app.slug)).map((app) =>
apps: APP_STORE_DEFINITIONS.filter((app) => (enableMcpAggregators || !isRemoteMcpConnectorId(app.slug)) && (enableMemoryConnectors || !isMemoryConnectorId(app.slug))).map((app) =>
appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles)
),
});
+10
View File
@@ -204,6 +204,16 @@ async function handleMcpGatewayProtocol(
} catch (err) {
if (err instanceof ToolGatewayHttpError) {
const id = (req.body as { id?: unknown } | undefined)?.id ?? null;
// Provider tool failures are MCP tool results, not successful calls or
// protocol errors. The service has already recorded the failed invocation.
if (req.body?.method === "tools/call" && err.reasonCode === "tool_error") {
res.json({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: err.message }], isError: true },
});
return;
}
res.status(err.status).json({
jsonrpc: "2.0",
id,
+115
View File
@@ -0,0 +1,115 @@
import { createHash } from "node:crypto";
/** Reviewed Cognee Cloud contract from cognee-mcp 0.5.5. Executed by the bundled bridge below. */
export const COGNEE_STDIO_TEMPLATE = {
name: "Cognee Cloud",
command: null,
args: [] as string[],
envKeys: ["COGNEE_BASE_URL", "COGNEE_API_KEY"],
tools: [
{
name: "remember", description: "Store text in a Cognee dataset or session.",
annotations: { readOnlyHint: false },
inputSchema: { type: "object", properties: {
data: { type: "string" }, dataset_name: { type: "string" },
session_id: { type: "string" }, custom_prompt: { type: "string" },
}, required: ["data"], additionalProperties: false },
},
{
name: "recall", description: "Search Cognee memory, optionally within named datasets or a session.",
annotations: { readOnlyHint: true },
inputSchema: { type: "object", properties: {
query: { type: "string" }, search_type: { type: "string" }, datasets: { type: "string" },
session_id: { type: "string" }, system_prompt: { type: "string" }, top_k: { type: "integer", minimum: 1, default: 15 },
}, required: ["query"], additionalProperties: false },
},
{
name: "forget", description: "Permanently delete a Cognee dataset, or all owned memory when everything is true.",
annotations: { destructiveHint: true },
inputSchema: { type: "object", properties: {
dataset: { type: "string" }, everything: { type: "boolean", default: false },
}, additionalProperties: false },
},
],
};
export function cogneeCloudUrl(value: string): URL {
const url = new URL(value);
if (url.protocol !== "https:" || !/^[a-z0-9-]+\.aws\.cognee\.ai$/i.test(url.hostname)
|| url.port || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
throw new Error("Copy the tenant API Base URL from Cognee's API Keys page.");
}
return url;
}
/**
* Bundled bridge for the three reviewed Cloud operations. No package manager,
* subprocess, runtime downloads, or inherited host environment is involved.
* The gateway supplies its DNS/redirect-guarded, response-bounded HTTP client.
*/
export async function callCogneeCloud(input: {
baseUrl: string;
apiKey: string;
tool: string;
parameters: Record<string, unknown>;
request: (url: URL, init: RequestInit) => Promise<unknown>;
signal: AbortSignal;
}) {
const base = cogneeCloudUrl(input.baseUrl);
if (!input.apiKey) throw new Error("Reconnect Cognee to restore its Cloud API key.");
const tenant = /^tenant-([0-9a-f-]{36})\./i.exec(base.hostname)?.[1];
const headers: Record<string, string> = { "X-Api-Key": input.apiKey };
if (tenant) headers["X-Tenant-Id"] = tenant;
const args = input.parameters;
const post = async (path: string, body: Record<string, unknown> | FormData) => {
const url = new URL(path, base);
const request = new Request(url, { method: "POST",
headers: body instanceof FormData ? headers : { ...headers, "Content-Type": "application/json" },
body: body instanceof FormData ? body : JSON.stringify(body) });
// The guarded client pins DNS through node:http and accepts byte buffers,
// not fetch's FormData. Serialize with the matching multipart boundary.
return input.request(url, { method: "POST", signal: input.signal,
headers: Object.fromEntries(request.headers), body: Buffer.from(await request.arrayBuffer()), redirect: "manual" });
};
let result: unknown;
if (input.tool === "remember") {
const dataset = args.dataset_name || "paperclip_memory";
if (args.session_id) {
if (args.custom_prompt) throw new Error("custom_prompt is not supported with session_id in Cognee Cloud.");
result = await post("/api/v1/remember/entry", {
entry: { type: "qa", question: "", answer: args.data, context: "" },
dataset_name: dataset, session_id: args.session_id,
});
} else {
const form = new FormData();
form.set("data", new Blob([String(args.data)], { type: "text/plain" }), `memory_${createHash("sha256").update(String(args.data)).digest("hex")}.txt`);
form.set("datasetName", String(dataset));
if (args.custom_prompt) form.set("custom_prompt", String(args.custom_prompt));
result = await post("/api/v1/remember", form);
}
} else if (input.tool === "recall") {
let datasets = typeof args.datasets === "string" ? args.datasets.split(",").map(v => v.trim()).filter(Boolean) : [];
if (!datasets.length && !args.session_id) {
const available = await input.request(new URL("/api/v1/datasets/", base), {
method: "GET", headers, signal: input.signal, redirect: "manual",
});
if (!Array.isArray(available)) throw new Error("Cognee returned an invalid dataset list.");
datasets = available.flatMap(value => value && typeof value.name === "string" ? [value.name] : []);
}
result = await post("/api/v1/recall", {
query: args.query, top_k: args.top_k ?? 15,
search_type: typeof args.search_type === "string" ? args.search_type.toUpperCase() : null,
...(datasets.length ? { datasets } : {}),
...(args.session_id ? { session_id: args.session_id } : {}),
...(args.system_prompt ? { system_prompt: args.system_prompt } : {}),
});
} else if (input.tool === "forget") {
if (!args.dataset && args.everything !== true) throw new Error("Specify a dataset or set everything to true.");
result = await post("/api/v1/forget", {
everything: args.everything === true, ...(args.dataset ? { dataset: args.dataset } : {}),
});
} else {
throw new Error("Unreviewed Cognee action.");
}
return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: { result }, isError: false };
}
+2
View File
@@ -235,6 +235,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
enableApps: true,
enableChatConnectors: parsed.data.enableChatConnectors ?? false,
enableMcpAggregators: parsed.data.enableMcpAggregators ?? false,
enableMemoryConnectors: parsed.data.enableMemoryConnectors ?? false,
enablePipelines: parsed.data.enablePipelines ?? false,
enableCases: parsed.data.enableCases ?? false,
enableAgentChat: parsed.data.enableAgentChat ?? false,
@@ -277,6 +278,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
enableApps: true,
enableChatConnectors: false,
enableMcpAggregators: false,
enableMemoryConnectors: false,
enablePipelines: false,
enableCases: false,
enableAgentChat: false,
@@ -0,0 +1,149 @@
import { describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { ToolGatewayHttpError, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js";
import { createAssignedMcpTools, getAssignedMcpGateway, registerAssignedMcpGateway } from "./assigned-mcp-tools.js";
function descriptor(name: string, risk: ToolGatewayDescriptor["risk"] = "read"): ToolGatewayDescriptor {
return { name, displayName: name, description: `Use ${name}`, parametersSchema: { type: "object", properties: { query: { type: "string" } } }, pluginId: "fixture", providerType: "mcp_remote_http", risk };
}
function fixture(tools: ToolGatewayDescriptor[]) {
const listToolsForNamedGateway = vi.fn().mockResolvedValue(tools);
const executeTool = vi.fn().mockResolvedValue({ status: "completed", result: { content: [{ type: "text", text: "memory found" }] } });
const gateway = { listToolsForNamedGateway, executeTool } as unknown as ToolGatewayService;
return { gateway, listToolsForNamedGateway, executeTool, gatewayPublicId: "gateway-fixture", bearerToken: "private-run-token-never-project" };
}
describe("assigned MCP runner tools", () => {
it("requires a configured gateway registered for the exact database instance", () => {
const firstDb = {} as Db;
const secondDb = {} as Db;
const first = fixture([]).gateway;
const second = fixture([]).gateway;
expect(() => getAssignedMcpGateway(firstDb)).toThrow("assigned_mcp_gateway_unavailable");
registerAssignedMcpGateway(firstDb, first);
expect(getAssignedMcpGateway(firstDb)).toBe(first);
expect(() => getAssignedMcpGateway(secondDb)).toThrow("assigned_mcp_gateway_unavailable");
registerAssignedMcpGateway(secondDb, second);
expect(getAssignedMcpGateway(secondDb)).toBe(second);
expect(getAssignedMcpGateway(firstDb)).toBe(first);
registerAssignedMcpGateway(firstDb, second);
expect(getAssignedMcpGateway(firstDb)).toBe(second);
});
it("projects only authorized gateway tools with stable bounded collision-resistant names", async () => {
const names = ["memory.search", "memory-search", "x".repeat(120), "🧠"];
const f = fixture(names.map(name => descriptor(name)));
const first = await createAssignedMcpTools(f);
const reversed = await createAssignedMcpTools({ ...f, gateway: fixture([...names].reverse().map(name => descriptor(name))).gateway });
const projected = first.definitions().map(tool => tool.name as string);
expect(new Set(projected).size).toBe(names.length);
for (const name of projected) {
expect(name).toMatch(/^app_[a-zA-Z0-9_]+_[a-f0-9]{12}$/);
expect(name.length).toBeLessThanOrEqual(64);
expect(first.has(name)).toBe(true);
}
expect(reversed.definitions().map(tool => tool.name)).toEqual([...projected].reverse());
expect(f.listToolsForNamedGateway).toHaveBeenCalledWith({ gatewayPublicId: f.gatewayPublicId, bearerToken: f.bearerToken });
});
it("keeps the provider and action readable for fully namespaced gateway tools", async () => {
const prefix = "mcp.app-gallery-mem0-60062edb-c211-4aae-a787-b4fa12a5ea24-f4ece062";
const tools = ["add-memory", "search-memories", "delete-memory"].map(action => ({
...descriptor(`${prefix}:${action}`), displayName: `Mem0 ${action}`,
}));
const assigned = await createAssignedMcpTools(fixture(tools));
for (const [index, definition] of assigned.definitions().entries()) {
const name = definition.name as string;
expect(name).toContain("mem0");
expect(name).toContain(tools[index]!.name.split(":").at(-1)!.replaceAll("-", "_"));
expect(name.length).toBeLessThanOrEqual(64);
expect(definition.description).toBe(`${tools[index]!.displayName}: ${tools[index]!.description}`);
}
const long = await createAssignedMcpTools(fixture([descriptor(`${prefix}:${"long-action-".repeat(10)}`)]));
expect((long.definitions()[0]!.name as string).length).toBeLessThanOrEqual(64);
});
it("does not project gateway secrets, URLs, or provider metadata and returns only the tool result", async () => {
const tool = { ...descriptor("recall"), providerMetadata: { token: "private-provider-token", url: "https://private-gateway.example" } };
const f = fixture([tool]);
f.executeTool.mockResolvedValue({ status: "completed", invocationId: "internal", result: { memories: [] } });
const assigned = await createAssignedMcpTools(f);
const definitions = assigned.definitions();
expect(Object.keys(definitions[0]!)).toEqual(["name", "description", "inputSchema"]);
expect(JSON.stringify(definitions)).not.toMatch(/private-|gateway-fixture|https:/);
const args = { query: "synthetic memory" };
expect(await assigned.execute({ tool: definitions[0]!.name as string, arguments: args })).toEqual({ memories: [] });
expect(f.executeTool).toHaveBeenCalledExactlyOnceWith({ gatewayPublicId: f.gatewayPublicId, sessionToken: f.bearerToken, tool: "recall", parameters: args });
(definitions[0]!.inputSchema as Record<string, unknown>).type = "string";
expect(assigned.definitions()[0]!.inputSchema).toEqual(tool.parametersSchema);
});
it("rejects unknown names without invoking the gateway", async () => {
const f = fixture([descriptor("recall")]);
const assigned = await createAssignedMcpTools(f);
expect(assigned.has("unassigned")).toBe(false);
await expect(assigned.execute({ tool: "unassigned", arguments: {} })).rejects.toThrow("assigned_mcp_tool_unknown");
expect(f.executeTool).not.toHaveBeenCalled();
});
it.each(["planning", "ask"] as const)("exposes and permits only read tools in %s mode", async workMode => {
const f = fixture([descriptor("read"), descriptor("remember", "write"), descriptor("forget", "destructive")]);
const standard = await createAssignedMcpTools(f);
const restricted = await createAssignedMcpTools({ ...f, workMode });
expect(restricted.definitions()).toEqual([standard.definitions()[0]]);
for (const tool of standard.definitions().slice(1)) {
await expect(restricted.execute({ tool: tool.name as string, arguments: {} })).rejects.toThrow("paperclip_runner_tool_mode_denied");
}
expect(f.executeTool).not.toHaveBeenCalled();
await restricted.execute({ tool: restricted.definitions()[0]!.name as string, arguments: {} });
expect(f.executeTool).toHaveBeenCalledOnce();
});
it("uses the gateway for write and destructive tools under standard mode without approval overrides", async () => {
const f = fixture([descriptor("remember", "write"), descriptor("forget", "destructive")]);
const assigned = await createAssignedMcpTools(f);
for (const tool of assigned.definitions()) await assigned.execute({ tool: tool.name as string, arguments: {} });
expect(f.executeTool).toHaveBeenCalledTimes(2);
for (const [call] of f.executeTool.mock.calls) expect(call).not.toHaveProperty("approvedActionRequestId");
});
it.each(["planning", "ask"] as const)("enforces fresh %s mode without relaxing the pinned mode", async currentMode => {
const f = fixture([descriptor("read"), descriptor("remember", "write")]);
const standard = await createAssignedMcpTools(f);
const restricted = await createAssignedMcpTools({ ...f, workMode: currentMode });
const write = { tool: standard.definitions()[1]!.name as string, arguments: {} };
await expect(standard.execute(write, currentMode)).rejects.toThrow("paperclip_runner_tool_mode_denied");
await expect(restricted.execute(write, "standard")).rejects.toThrow("paperclip_runner_tool_mode_denied");
expect(f.executeTool).not.toHaveBeenCalled();
await standard.execute({ tool: standard.definitions()[0]!.name as string, arguments: {} }, currentMode);
expect(f.executeTool).toHaveBeenCalledOnce();
});
it.each(["tool_error", "approval_required", "connection_revoked"])("propagates %s without converting it to success", async reason => {
const f = fixture([descriptor("recall")]);
const error = new ToolGatewayHttpError(403, "Gateway refused execution", reason);
f.executeTool.mockRejectedValue(error);
const assigned = await createAssignedMcpTools(f);
await expect(assigned.execute({ tool: assigned.definitions()[0]!.name as string, arguments: {} })).rejects.toBe(error);
});
it("propagates discovery denial", async () => {
const f = fixture([]);
const error = new Error("gateway_token_revoked");
f.listToolsForNamedGateway.mockRejectedValue(error);
await expect(createAssignedMcpTools(f)).rejects.toBe(error);
});
it("rejects error payloads and incomplete outcomes, and accepts successful replay", async () => {
const f = fixture([descriptor("recall")]);
const assigned = await createAssignedMcpTools(f);
const call = { tool: assigned.definitions()[0]!.name as string, arguments: {} };
f.executeTool.mockResolvedValueOnce({ status: "completed", result: { isError: true, content: [] } });
await expect(assigned.execute(call)).rejects.toMatchObject({ reasonCode: "tool_error" });
f.executeTool.mockResolvedValueOnce({ status: "pending", result: {} });
await expect(assigned.execute(call)).rejects.toThrow("assigned_mcp_tool_execution_incomplete");
f.executeTool.mockResolvedValueOnce({ status: "replayed", result: { memory: "synthetic" } });
await expect(assigned.execute(call)).resolves.toEqual({ memory: "synthetic" });
});
});
@@ -0,0 +1,85 @@
import { createHash } from "node:crypto";
import type { Db } from "@paperclipai/db";
import { ToolGatewayHttpError, type ToolGatewayDescriptor, type ToolGatewayService } from "../tool-gateway.js";
type WorkMode = "standard" | "planning" | "ask";
// Execution must use the app's configured gateway, including deployment
// restrictions, OAuth refresh, and approval delivery. Never fall back to an
// isolated gateway whose defaults differ from the running instance.
const assignedMcpGateways = new WeakMap<Db, ToolGatewayService>();
export function registerAssignedMcpGateway(db: Db, gateway: ToolGatewayService): void {
assignedMcpGateways.set(db, gateway);
}
export function getAssignedMcpGateway(db: Db): ToolGatewayService {
const gateway = assignedMcpGateways.get(db);
if (!gateway) throw new Error("assigned_mcp_gateway_unavailable");
return gateway;
}
function assignedToolName(name: string): string {
const sanitize = (value: string) => value.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
const separator = name.lastIndexOf(":");
const readable = separator >= 0
? `${sanitize(name.slice(0, separator)).slice(0, 20) || "tool"}_${sanitize(name.slice(separator + 1)).slice(-26) || "action"}`
: sanitize(name).slice(0, 47) || "tool";
const digest = createHash("sha256").update(name).digest("hex").slice(0, 12);
return `app_${readable}_${digest}`;
}
/** Server-owned MCP bindings projected into the runner's existing tool channel. */
export async function createAssignedMcpTools(input: {
gateway: ToolGatewayService;
gatewayPublicId: string;
bearerToken: string;
workMode?: WorkMode;
}) {
const listed = await input.gateway.listToolsForNamedGateway({
gatewayPublicId: input.gatewayPublicId,
bearerToken: input.bearerToken,
});
const tools = new Map<string, ToolGatewayDescriptor>();
for (const descriptor of listed) {
const name = assignedToolName(descriptor.name);
if (tools.has(name)) throw new Error("assigned_mcp_tool_name_collision");
tools.set(name, descriptor);
}
const permits = (tool: ToolGatewayDescriptor, mode: WorkMode = input.workMode ?? "standard") => mode === "standard" || tool.risk === "read";
return {
definitions(): Array<Record<string, unknown>> {
return [...tools].filter(([, tool]) => permits(tool)).map(([name, tool]) => ({
name,
description: `${tool.displayName}: ${tool.description}`,
inputSchema: structuredClone(tool.parametersSchema),
}));
},
has(name: string): boolean {
return tools.has(name);
},
async execute(call: { tool: string; arguments: unknown }, currentWorkMode?: WorkMode): Promise<unknown> {
const descriptor = tools.get(call.tool);
if (!descriptor) throw new Error("assigned_mcp_tool_unknown");
if (!permits(descriptor) || !permits(descriptor, currentWorkMode)) throw new Error("paperclip_runner_tool_mode_denied");
// Reauthorize through the existing gateway on every call. Discovery is
// not a grant: revocation, policy, approval, and audit remain server-owned.
const result = await input.gateway.executeTool({
gatewayPublicId: input.gatewayPublicId,
sessionToken: input.bearerToken,
tool: descriptor.name,
parameters: call.arguments,
});
if (result.status !== "completed" && result.status !== "replayed") {
throw new Error("assigned_mcp_tool_execution_incomplete");
}
// The gateway normally throws provider errors. Keep a malformed or older
// provider response from being reported as successful through PRP.
if (result.result && typeof result.result === "object" && "isError" in result.result && result.result.isError === true) {
throw new ToolGatewayHttpError(502, "The assigned tool returned an error.", "tool_error");
}
return result.result;
},
};
}
@@ -127,6 +127,7 @@ const durableRunnerState = (
});
const state = vi.hoisted(() => ({
createAssignedMcpTools: vi.fn(),
execute: vi.fn(),
cleanup: vi.fn(),
retireCleanup: vi.fn(),
@@ -219,6 +220,11 @@ vi.mock("./paperclip-runner-tool-authority.js", () => ({
},
}));
vi.mock("./assigned-mcp-tools.js", () => ({
createAssignedMcpTools: state.createAssignedMcpTools,
getAssignedMcpGateway: () => ({}),
}));
vi.mock("./native-runner-file-handoff.js", () => ({
stageNativeRunnerWakeAttachments: state.stageNativeRunnerWakeAttachments,
renderNativeRunnerStagedAttachmentPrompt:
@@ -304,6 +310,7 @@ import {
} from "./native-session-executor.js";
beforeEach(() => {
state.createAssignedMcpTools.mockReset();
state.resolveRunnerBinary.mockReset().mockReturnValue("/tmp/paperclip-runnerd");
state.resolveCurrentWakeCommentsBinding.mockReset().mockResolvedValue(null);
state.assertCurrentWakeCommentsRead.mockReset().mockResolvedValue(undefined);
@@ -7997,6 +8004,52 @@ describe("runnerd provider runtime wiring", () => {
}
});
it.each([
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned" },
{ PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/test" },
{ PAPERCLIP_NATIVE_MCP_TOKEN: "private-run-token" },
])("rejects partial remote assigned MCP bindings", async (runnerEnvironment) => {
await expect(createRunnerdBackend({
db: leaseDb(execution), execution, runnerInstanceId: "runner-partial-mcp", runnerEnvironment,
runnerExecutionTarget: {
kind: "remote", transport: "sandbox", providerKey: "daytona",
leaseId: "lease-partial-mcp", remoteCwd: "/home/daytona/paperclip-workspace",
runner: { execute: vi.fn() },
} as never,
})).rejects.toThrow("assigned native MCP launch binding is incomplete");
expect(state.createAssignedMcpTools).not.toHaveBeenCalled();
});
it("keeps assigned MCP credentials on the control plane for remote Codex", async () => {
const assignedMcpTools = { definitions: () => [], has: () => false, execute: vi.fn() };
state.createAssignedMcpTools.mockResolvedValueOnce(assignedMcpTools);
state.createBackend.mockClear();
state.createTransport.mockClear();
state.toolAuthorityDefinitions.mockClear();
await createRunnerdBackend({
db: leaseDb(execution), execution, runnerInstanceId: "runner-assigned-mcp",
runnerEnvironment: {
PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",
PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/assigned-test",
PAPERCLIP_NATIVE_MCP_TOKEN: "private-run-token",
},
runnerExecutionTarget: {
kind: "remote", transport: "sandbox", providerKey: "daytona",
leaseId: "lease-assigned-mcp", remoteCwd: "/home/daytona/paperclip-workspace",
runner: { execute: vi.fn() },
} as never,
});
expect(state.createAssignedMcpTools).toHaveBeenCalledWith(expect.objectContaining({
gatewayPublicId: "assigned-test", bearerToken: "private-run-token",
}));
expect(state.toolAuthorityDefinitions).toHaveBeenCalledWith(expect.objectContaining({ assignedMcpTools }));
state.createBackend.mock.calls[0]![1].codexTransportFactory!();
const options = state.createTransport.mock.calls[0]![0] as { environment: NodeJS.ProcessEnv };
expect(options.environment.PAPERCLIP_NATIVE_MCP_NAME).toBeUndefined();
expect(options.environment.PAPERCLIP_NATIVE_MCP_URL).toBeUndefined();
expect(options.environment.PAPERCLIP_NATIVE_MCP_TOKEN).toBeUndefined();
});
it("makes remote authority archival idempotent and returns the archived state", async () => {
const remoteExecute = vi.fn();
const remoteTarget = {
@@ -122,6 +122,7 @@ import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
import { nativeSha256 } from "./canonical.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
import { createAssignedMcpTools, getAssignedMcpGateway } from "./assigned-mcp-tools.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
import { NativeChatAttachmentReadScope } from "./chat-attachment-read.js";
import {
@@ -10463,9 +10464,35 @@ async function createRunnerdBackendWithinSessionClaim(
if (nativeReview && !await getNativeReviewAssignment(input.db, {
...input.execution.binding, contextSnapshot: nativeReview,
})) throw new Error("native_review_assignment_no_longer_available");
// Remote Codex already sends dynamic tool calls over authenticated PRP. Keep
// the assigned gateway on the control plane instead of asking the sandbox to
// reach the host's HTTP origin (which may be private or loopback-only).
const relayAssignedMcp = remoteTarget !== null && input.execution.provider.kind === "codex";
const assignedMcpUrl = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_URL;
const assignedMcpToken = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_TOKEN;
const assignedMcpName = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_NAME;
const hasAssignedMcp = Boolean(assignedMcpName || assignedMcpUrl || assignedMcpToken);
if (relayAssignedMcp && hasAssignedMcp && (!assignedMcpName?.trim() || !assignedMcpUrl?.trim() || !assignedMcpToken?.trim())) {
throw new Error("assigned native MCP launch binding is incomplete");
}
const assignedGatewayPublicId = relayAssignedMcp && assignedMcpUrl
? new URL(assignedMcpUrl).pathname.match(/^\/mcp\/gateways\/([a-zA-Z0-9_-]+)$/)?.[1]
: undefined;
if (relayAssignedMcp && hasAssignedMcp && !assignedGatewayPublicId) {
throw new Error("assigned native MCP gateway path is invalid");
}
const assignedMcpTools = relayAssignedMcp && !nativeReview && assignedMcpUrl && assignedMcpToken
? await createAssignedMcpTools({
gateway: getAssignedMcpGateway(input.db),
gatewayPublicId: assignedGatewayPublicId!,
bearerToken: assignedMcpToken,
workMode: input.execution.task.workMode,
})
: undefined;
const authority = new PaperclipRunnerToolAuthority(input.db, {
...(nativeReview ? { nativeReview } : {}),
connectorAssignments: connectorAssignments.filter((assignment) => pinnedSkills.has(assignment.skillKey)),
assignedMcpTools,
companyId: input.execution.binding.companyId,
issueId: input.execution.binding.issueId,
runId: input.execution.binding.runId,
@@ -12024,6 +12051,13 @@ async function createRunnerdBackendWithinSessionClaim(
const effectiveRunnerEnvironmentBase: NodeJS.ProcessEnv = {
...(input.runnerEnvironment ?? process.env),
};
if (relayAssignedMcp) {
// The server-held tool authority owns this credential. Do not deliver a
// duplicate HTTP MCP server or its bearer token to the remote provider.
delete effectiveRunnerEnvironmentBase.PAPERCLIP_NATIVE_MCP_NAME;
delete effectiveRunnerEnvironmentBase.PAPERCLIP_NATIVE_MCP_URL;
delete effectiveRunnerEnvironmentBase.PAPERCLIP_NATIVE_MCP_TOKEN;
}
// This authority bit is derived only from the selected execution target.
// Never let an agent, environment binding, or host variable disable the
// Codex sandbox for a local runner by supplying the same key.
@@ -38,6 +38,9 @@ export function nativeToolContractFingerprintForTarget(
"always_advertised_run_issue_agent_binding_gated_current_task_description.v2",
semanticCompletion: "finish_accessible_deliverable_evidence.v4",
connectorTools: "assigned_resources_and_pinned_skill_bundle.v1",
...(executionTargetKind === "remote"
? { assignedMcpTools: "codex_server_gateway_prp_relay.v1" }
: {}),
},
tools: [
{ name: "register_deliverable", version: 2 },
@@ -596,6 +596,34 @@ describe("PaperclipRunnerToolAuthority", () => {
).resolves.toMatchObject({ approval: { id: approvalId }, tasks: [] });
});
it("relays assigned MCP calls only while the native run still owns its task", async () => {
const tool = { name: "app_mem0_recall", description: "Recall memory", inputSchema: { type: "object" } };
const execute = vi.fn().mockResolvedValue({ content: "synthetic memory" });
const authority = new PaperclipRunnerToolAuthority(db, {
companyId, agentId, issueId, runId,
assignedMcpTools: { definitions: () => [tool], has: (name) => name === tool.name, execute },
});
expect(authority.definitions()).toContainEqual(tool);
const call = { tool: tool.name, callId: "assigned-mcp", arguments: { query: "compass" } };
await expect(authority.execute(call)).resolves.toEqual({ content: "synthetic memory" });
expect(execute).toHaveBeenCalledWith(call, "standard");
await db.update(issues).set({ workMode: "ask" }).where(eq(issues.id, issueId));
try {
await authority.execute(call);
expect(execute).toHaveBeenLastCalledWith(call, "ask");
} finally {
await db.update(issues).set({ workMode: "standard" }).where(eq(issues.id, issueId));
}
execute.mockClear();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, runId));
try {
await expect(authority.execute(call)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
expect(execute).not.toHaveBeenCalled();
} finally {
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
}
});
it("does not advertise delegation tools during pre-acceptance planning", () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
@@ -1,4 +1,5 @@
import { publicChatTaskUrl } from "../chat-task-url.js";
import type { createAssignedMcpTools } from "./assigned-mcp-tools.js";
import { assertAssignableAgent } from "../agent-assignability.js";
import { authorizationService } from "../authorization.js";
import { handoffPlanContext } from "./handoff-plan-context.js";
@@ -104,6 +105,7 @@ type Binding = {
storage?: StorageService;
/** Server-owned suppression for baseline evals; true never overrides operator opt-in. */
connectorAssignments?: ConnectorAssignment[];
assignedMcpTools?: Awaited<ReturnType<typeof createAssignedMcpTools>>;
apiToolsEnabled?: boolean;
workMode?: "standard" | "planning" | "ask";
workspaceRoot?: string;
@@ -223,7 +225,7 @@ export class PaperclipRunnerToolAuthority {
definitions.push(LIST_CHAT_ATTACHMENTS_TOOL_DEFINITION);
definitions.push(REUSE_CHAT_ATTACHMENT_TOOL_DEFINITION);
definitions.push(READ_CHAT_ATTACHMENT_TOOL_DEFINITION);
return [...RUNTIME_CONNECTION_TOOL_DEFINITIONS, ...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools), ...definitions];
return [...RUNTIME_CONNECTION_TOOL_DEFINITIONS, ...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools), ...(this.binding.assignedMcpTools?.definitions() ?? []), ...definitions];
}
async execute(call: {
@@ -237,6 +239,10 @@ export class PaperclipRunnerToolAuthority {
throw forbidden("This review run may only inspect the assigned task and resolve its review.");
}
}
if (this.binding.assignedMcpTools?.has(call.tool)) {
const current = await this.#boundContext();
return this.binding.assignedMcpTools.execute(call, current.issue.workMode as "standard" | "planning" | "ask");
}
if (isConnectorTool(call.tool)) {
if (!(this.binding.connectorAssignments ?? []).some((assignment) => assignment.tools.some((tool) => tool.name === call.tool))) throw forbidden("Connector tool is not available to this run");
const { run } = await this.#boundContext();
+108 -31
View File
@@ -1,4 +1,5 @@
import { isRemoteMcpConnectorMethod, connectionPurposeTransportSchema } from "@paperclipai/shared";
import { COGNEE_STDIO_TEMPLATE, cogneeCloudUrl } from "./cognee-connection.js";
import { isMemoryConnectorId, isRemoteMcpConnectorMethod, connectionPurposeTransportSchema } from "@paperclipai/shared";
import { instanceSettingsService } from "./instance-settings.js";
import { githubBotRequest } from "./chat-github-client.js";
import { syncConnectionCredentialBindings } from "./connection-credential-bindings.js";
@@ -815,6 +816,7 @@ const APPROVED_STDIO_TEMPLATES: Record<
},
],
},
"paperclip.cognee-cloud": COGNEE_STDIO_TEMPLATE,
"paperclip.google-sheets": {
name: "Google Sheets",
command: "paperclip-google-sheets-mcp-server",
@@ -1040,7 +1042,7 @@ function credentialFieldsFor(app: AppDefinition, methodKey?: string | null) {
const method = connectionMethodFor(app, methodKey);
return (method.credentialFields ?? []).map((field) => ({
label: field.label,
configPath: credentialConfigPath(field),
configPath: credentialConfigPath(field, method),
helpUrl: method.consoleLinks?.keys ?? method.consoleLinks?.docs ?? "",
required: field.required,
placement:
@@ -2342,6 +2344,15 @@ export function classifyRisk(
if (annotations.destructiveHint === true || annotations.destructive === true)
return "destructive";
const normalizedToolName = normalizedProviderToolName(tool.name);
if (isMemoryConnectorId(sourceTemplateKey)) {
if (verbMatches(tool.name, "delete|remove|destroy|forget|prune|reset")) return "destructive";
// Supermemory uses one add_memory tool for both save and forget.
if (sourceTemplateKey === "supermemory" && normalizedToolName === "add-memory") return "destructive";
if (verbMatches(tool.name, "add|remember|save|record|ingest|cognify|update|create|set|upload|select|rename|share")) return "write";
if (annotations.readOnlyHint === false || annotations.writeHint === true) return "write";
const reads = ["get", "list", "search", "recall", "query", "retrieve", "who"];
return verbMatches(tool.name, reads.join("|")) ? "read" : "write";
}
const reviewedReads = AGGREGATOR_READ_TOOLS.get(sourceTemplateKey ?? "");
if (reviewedReads) {
if (verbMatches(tool.name, "delete|remove|destroy|unpublish")) return "destructive";
@@ -2827,6 +2838,7 @@ function healthFailureHttpStatus(failure: {
if (failure.code === "user_authorization_required") return 422;
if (failure.code === "composio_broker_retired") return 422;
if (failure.code === "tool_connection_transport_unsupported") return 422;
if (failure.code === "cognee_access_unverified" || failure.code === "memory_api_key_rejected") return 422;
if (failure.code.endsWith("_endpoint_rejected")) return 422;
return 502;
}
@@ -2845,6 +2857,9 @@ function sanitizeHttpFailure(error: unknown): {
} {
if (error instanceof HttpError) {
const code = asRecord(error.details).code;
if (code === "cognee_access_unverified" || code === "memory_api_key_rejected") {
return { status: "error", message: error.message, code };
}
if (code === "slack_mcp_access_disabled") {
return { status: "error", message: error.message, code };
}
@@ -3509,7 +3524,9 @@ export function toolAccessService(
function assertLocalStdioCanBeEnabled(
transport: ToolConnectionTransport,
enabled: boolean,
config: Record<string, unknown> = {},
) {
if (config.templateId === "paperclip.cognee-cloud") return;
if (
transport === "local_stdio" &&
enabled &&
@@ -6496,7 +6513,7 @@ export function toolAccessService(
async function ensureRuntimeSlot(
connection: typeof toolConnections.$inferSelect,
): Promise<ToolRuntimeSlot | null> {
if (connection.transport !== "local_stdio") return null;
if (connection.transport !== "local_stdio" || connection.config.templateId === "paperclip.cognee-cloud") return null;
const slotKey = `mcp:${connection.companyId}:${connection.id}`;
const [existing] = await db
.select()
@@ -6883,6 +6900,10 @@ export function toolAccessService(
}
}
if (!response.ok) {
if ((response.status === 401 || response.status === 403)
&& connection.authKind === "api_key" && isMemoryConnectorId(connection.config.sourceTemplateKey)) {
throw unprocessable("The provider rejected this API key. Check the key and its account access, then try again.", { code: "memory_api_key_rejected" });
}
if (await isSlackMcpAccessDisabledResponse(endpoint, response)) {
throw unprocessable(
"Slack MCP access is disabled for this app. Ask the Slack app owner to enable MCP access, then refresh this connection.",
@@ -6990,6 +7011,34 @@ export function toolAccessService(
return apiStatus === "available" ? [...descriptors, ...RAILWAY_TOOLS] : descriptors;
}
async function validateCogneeConnection(connection: typeof toolConnections.$inferSelect, actor?: ActorInfo, probe = true) {
if (connection.config.templateId !== "paperclip.cognee-cloud") return;
const grant = await vaultGrantForConnection(connection, actor);
const refs = grant?.credentialSecretRefs ?? connection.credentialSecretRefs;
const values: Record<string, string> = {};
for (const key of COGNEE_STDIO_TEMPLATE.envKeys) {
const ref = refs.find((candidate) => candidate.configPath === `env.${key}`);
if (!ref) throw unprocessable("Reconnect Cognee to restore its Cloud credentials", { code: "missing_secret" });
values[key] = grant
? (await resolveOAuthGrantSecret(connection, grant, ref, actor, undefined)).value
: await secrets.resolveSecretValue(connection.companyId, ref.secretId, ref.versionSelector ?? "latest", {
consumerType: "tool_connection", consumerId: connection.id, configPath: ref.configPath,
actorType: "system", actorId: null,
});
}
let base: URL;
try { base = cogneeCloudUrl(values.COGNEE_BASE_URL!); }
catch { throw badRequest("Copy the tenant API Base URL from Cognee’s API Keys page."); }
// Scheduled health checks validate configuration and vault access. A transient
// Cloud probe must not withdraw an already assigned local tool catalog.
if (!probe) return;
const response = await requestRemoteHttpEndpoint(new URL("/api/v1/datasets/", base), {
method: "GET", headers: { "X-Api-Key": values.COGNEE_API_KEY! }, signal: AbortSignal.timeout(15_000),
});
await response.body?.cancel();
if (!response.ok) throw unprocessable("Cognee Cloud could not verify access. Check the tenant URL, API key, and workspace subscription.", { code: "cognee_access_unverified" });
}
async function localTools(
connection: typeof toolConnections.$inferSelect,
): Promise<McpToolDescriptor[]> {
@@ -7062,6 +7111,7 @@ export function toolAccessService(
throw unsupportedToolConnectionTransport();
}
await resolveCredentialHeaders(connection);
await validateCogneeConnection(connection, actor);
return localTools(connection);
}
@@ -7223,6 +7273,7 @@ export function toolAccessService(
} else if (connection.transport === "local_stdio") {
await resolveCredentialHeaders(connection);
await stdioTemplateId(connection.companyId, connection.config);
await validateCogneeConnection(connection, actor, false);
} else {
throw unsupportedToolConnectionTransport();
}
@@ -11818,7 +11869,11 @@ export function toolAccessService(
return `${base.slice(0, 151).trimEnd()} (${randomUUID().slice(0, 6)})`;
}
async function assertMcpAggregatorSetupEnabled(provider: unknown, method: unknown) {
async function assertExperimentalConnectorSetupEnabled(provider: unknown, method: unknown, existing = false) {
if (!existing && isMemoryConnectorId(provider)
&& !(await instanceSettingsService(db).getExperimental()).enableMemoryConnectors) {
throw forbidden("Enable memory connectors in Settings → Experimental to set up this connection", { code: "memory_connectors_disabled" });
}
if (isRemoteMcpConnectorMethod(provider, method)
&& !(await instanceSettingsService(db).getExperimental()).enableMcpAggregators) {
throw forbidden("Enable MCP aggregators in Settings → Experimental to set up this connection", {
@@ -11975,7 +12030,10 @@ export function toolAccessService(
? connectionMethodFor(galleryEntry, inferredMethodKey)
: null;
const remoteMcpConnector = isRemoteMcpConnectorMethod(galleryEntry?.slug, method?.key);
await assertMcpAggregatorSetupEnabled(galleryEntry?.slug, method?.key);
await assertExperimentalConnectorSetupEnabled(galleryEntry?.slug, method?.key, Boolean(
input.reconnectConnectionId && requestedResumeConnection?.status !== "draft"
&& requestedResumeConnection?.config.sourceTemplateKey === galleryEntry?.slug,
));
if (galleryEntry && input.link) {
const acceptsProviderGeneratedUrl =
method?.transport === "mcp_remote" &&
@@ -12403,6 +12461,7 @@ export function toolAccessService(
[];
const credentialRefs: McpConnectionCredentialRef[] = [];
const createdSecretIds: string[] = [];
const createdDefinitionIds: string[] = [];
// "Just me" needs a named board user to own the consent. An agent actor
// cannot hold a personal identity, and silently falling back to a shared
// credential is exactly the mis-scoping the design forbids, so refuse.
@@ -12498,17 +12557,28 @@ export function toolAccessService(
throw badRequest(`Missing credential value for ${field.configPath}`);
}
if (!value) continue;
const secret = await secrets.create(
companyId,
{
name: `${name} ${field.label} ${randomUUID().slice(0, 8)}`,
key: `tool_app.${randomUUID()}.${field.configPath.replace(/[^a-z0-9_:-]+/gi, "_")}`,
provider: "local_encrypted",
value,
description: `Credential for ${name} (${field.configPath}).`,
},
actorForSecret(actor),
);
const secretMetadata = {
name: `${name} ${field.label} ${randomUUID().slice(0, 8)}`,
key: `tool_app.${randomUUID()}.${field.configPath.replace(/[^a-z0-9_:-]+/gi, "_")}`,
provider: "local_encrypted" as const,
description: `Credential for ${name} (${field.configPath}).`,
};
// A personal grant must own a user-scoped vault value. Merely keeping a
// company secret off the connection row does not establish ownership.
const secret = personalIdentityUserId
? await db.transaction(async (tx) => {
const personalSecrets = secretService(tx as unknown as Db);
const definition = await personalSecrets.createUserSecretDefinition(
companyId, secretMetadata, actorForSecret(actor),
);
const valueRow = await personalSecrets.createCurrentUserSecretValue(
companyId, personalIdentityUserId,
{ definitionId: definition.id, value }, actorForSecret(actor),
);
createdDefinitionIds.push(definition.id);
return valueRow;
})
: await secrets.create(companyId, { ...secretMetadata, value }, actorForSecret(actor));
createdSecretIds.push(secret.id);
credentialSecretRefs.push({
secretId: secret.id,
@@ -13247,6 +13317,9 @@ export function toolAccessService(
for (const secretId of createdSecretIds) {
await secrets.remove(secretId).catch(() => undefined);
}
for (const definitionId of createdDefinitionIds) {
await db.delete(userSecretDefinitions).where(eq(userSecretDefinitions.id, definitionId)).catch(() => undefined);
}
}
if (identityRollbackError) {
throw new HttpError(
@@ -13887,7 +13960,7 @@ export function toolAccessService(
): Promise<ToolConnectionHealthCheckResult> {
const connection = await getConnectionRow(connectionId, companyId);
assertSupportedConnection(connection);
await assertMcpAggregatorSetupEnabled(connection.config.sourceTemplateKey, connection.config.connectionMethodKey);
await assertExperimentalConnectorSetupEnabled(connection.config.sourceTemplateKey, connection.config.connectionMethodKey, connection.status !== "draft");
if (connection.status === "archived")
throw conflict("Archived app connections cannot be reconnected");
if (connection.credentialSource === "vercel_connect") {
@@ -13956,17 +14029,20 @@ export function toolAccessService(
);
continue;
}
const secret = await secrets.create(
companyId,
{
name: `${connection.name} ${field.label} ${randomUUID().slice(0, 8)}`,
key: `tool_app.${randomUUID()}.${field.configPath.replace(/[^a-z0-9_:-]+/gi, "_")}`,
provider: "local_encrypted",
value,
description: `Credential for ${connection.name} (${field.configPath}).`,
},
actorForSecret(actor),
);
const metadata = {
name: `${connection.name} ${field.label} ${randomUUID().slice(0, 8)}`,
key: `tool_app.${randomUUID()}.${field.configPath.replace(/[^a-z0-9_:-]+/gi, "_")}`,
provider: "local_encrypted" as const,
description: `Credential for ${connection.name} (${field.configPath}).`,
};
const secret = personalIdentity
? await db.transaction(async (tx) => {
const vault = secretService(tx as unknown as Db);
const definition = await vault.createUserSecretDefinition(companyId, metadata, actorForSecret(actor));
return vault.createCurrentUserSecretValue(companyId, personalIdentity.subjectUserId,
{ definitionId: definition.id, value }, actorForSecret(actor));
})
: await secrets.create(companyId, { ...metadata, value }, actorForSecret(actor));
credentialSecretRefs.push({
secretId: secret.id,
versionSelector: "latest",
@@ -14063,7 +14139,7 @@ export function toolAccessService(
): Promise<ToolOAuthStartResult> {
let connection = await getConnectionRow(connectionId, companyId);
assertSupportedConnection(connection);
await assertMcpAggregatorSetupEnabled(connection.config.sourceTemplateKey, connection.config.connectionMethodKey);
await assertExperimentalConnectorSetupEnabled(connection.config.sourceTemplateKey, connection.config.connectionMethodKey, connection.status !== "draft");
if (connection.status === "archived")
throw conflict("Archived app connections cannot start sign in");
const sourceTemplateKey =
@@ -16560,7 +16636,7 @@ export function toolAccessService(
if (!app || app.availability?.available === false)
throw notFound("App not found");
const method = connectionMethodFor(app, methodKey);
await assertMcpAggregatorSetupEnabled(app.slug, method.key);
await assertExperimentalConnectorSetupEnabled(app.slug, method.key);
if (method.transport !== "mcp_remote" || !method.defaults?.serverUrl) {
throw unprocessable(
"This app method does not use a hosted remote MCP endpoint",
@@ -17358,7 +17434,7 @@ export function toolAccessService(
if (transport === "mcp_remote")
await assertRemoteConnectionEndpointsAllowed(config);
if (transport === "local_stdio") await stdioTemplateId(companyId, config);
assertLocalStdioCanBeEnabled(transport, input.enabled ?? false);
assertLocalStdioCanBeEnabled(transport, input.enabled ?? false, config);
await assertGoogleSheetsSpreadsheetOwnership(companyId, config);
if (applicationId) {
const app = await assertApplication(companyId, applicationId);
@@ -18282,6 +18358,7 @@ export function toolAccessService(
assertLocalStdioCanBeEnabled(
existing.transport,
input.enabled ?? existing.enabled,
config,
);
await assertGoogleSheetsSpreadsheetOwnership(existing.companyId, config, {
excludeConnectionId: existing.id,
+66 -15
View File
@@ -1,3 +1,4 @@
import { COGNEE_STDIO_TEMPLATE, cogneeCloudUrl, callCogneeCloud } from "./cognee-connection.js";
import { HttpError } from "../errors.js";
import { claimSlackRateLimitRetry } from "./connectors/slack-retry.js";
import { resolveSlackTaskAuthority } from "./connectors/slack-authority.js";
@@ -423,6 +424,7 @@ const BUILTIN_LOCAL_STDIO_RUNTIME_TEMPLATES: Record<
string,
Omit<LocalStdioRuntimeTemplate, "templateId">
> = {
"paperclip.cognee-cloud": COGNEE_STDIO_TEMPLATE,
"paperclip.google-sheets": {
command: "paperclip-google-sheets-mcp-server",
args: [],
@@ -4097,10 +4099,10 @@ export function createToolGatewayService(
connection,
grant,
grantRef,
// OAuth grants declare their canonical oauth.* path. Treating
// this header projection as a generic credentials.* binding loses
// the personal secret declaration created by the OAuth callback.
grantRef.configPath.startsWith("oauth.")
// Personal grants resolve against their declared vault path. API-key
// paths already include credentials.* or headers.*; prepending again
// breaks the declaration just as it does for OAuth token paths.
grant.kind === "user" || grantRef.configPath.startsWith("oauth.")
? grantRef.configPath
: `credentials.${ref.name}`,
);
@@ -4936,6 +4938,12 @@ export function createToolGatewayService(
);
}
}
if (template.templateId === "paperclip.cognee-cloud") {
try { cogneeCloudUrl(env.COGNEE_BASE_URL ?? ""); }
catch {
throw new ToolGatewayHttpError(422, "Reconnect Cognee with the tenant API Base URL from its API Keys page.", "cognee_cloud_url_invalid");
}
}
return env;
}
@@ -4961,6 +4969,27 @@ export function createToolGatewayService(
protocolParams?: Record<string, unknown>;
timeoutMs: number;
}): Promise<unknown> {
if (input.template.templateId === "paperclip.cognee-cloud") {
if (input.protocolMethod === "resources/list") return { resources: [] };
if (input.protocolMethod === "prompts/list") return { prompts: [] };
if (input.protocolMethod && input.protocolMethod !== "tools/call") {
throw stdioProtocolError("Cognee does not expose this context operation");
}
return callCogneeCloud({
baseUrl: input.env.COGNEE_BASE_URL ?? "", apiKey: input.env.COGNEE_API_KEY ?? "",
tool: input.entry?.toolName ?? "", parameters: asRecord(input.parameters) ?? {},
signal: AbortSignal.timeout(input.timeoutMs),
request: async (url, init) => {
const response = await guardedRemoteHttpFetch(url, init, remoteHttpFetchOptions());
const body = await readBoundedRemoteResponse(response);
if (!response.ok) throw new ToolGatewayHttpError(502,
`Cognee Cloud request failed (HTTP ${response.status}).`, "cognee_api_error");
if (!body) return { status: "success" };
try { return JSON.parse(body); }
catch { throw new ToolGatewayHttpError(502, "Cognee Cloud returned invalid JSON.", "cognee_api_error"); }
},
});
}
if (!input.template.command) {
throw new ToolGatewayHttpError(
501,
@@ -5286,6 +5315,10 @@ export function createToolGatewayService(
template,
grant,
);
if (template.templateId === "paperclip.cognee-cloud") {
return callLocalStdioMcp({ connection: input.connection, template, env,
protocolMethod: input.method, protocolParams: input.params ?? {}, timeoutMs: DEFAULT_TOOL_TIMEOUT_MS });
}
return runtimeSupervisor.useConnectionSlot(
{
companyId: input.session.companyId,
@@ -5784,7 +5817,7 @@ export function createToolGatewayService(
function normalizeMcpToolResult(
result: unknown,
transport: "mcp_http" | "local_stdio" = "mcp_http",
transport: "mcp_http" | "local_stdio" | "cognee_cloud" = "mcp_http",
spawnedLocalProcess = false,
sourceTemplateKey?: string | null,
) {
@@ -6254,6 +6287,7 @@ export function createToolGatewayService(
tool: ToolGatewayDescriptor,
parameters: unknown,
ms: number,
useProviderDefaultTimeout = false,
): Promise<RemoteHttpExecutionResult> {
const { entry, connection } = await resolveConnectedLocalStdioTool(
session,
@@ -6267,7 +6301,13 @@ export function createToolGatewayService(
template,
grant,
);
const result = await runtimeSupervisor.useConnectionSlot(
const invoke = () => callLocalStdioMcp({ connection, entry, template, env, parameters,
timeoutMs: useProviderDefaultTimeout && template.templateId === "paperclip.cognee-cloud" ? 60_000 : ms });
// Cognee is a bundled HTTP client. Provider failures are tool failures, not
// crashed local processes, and must never consume slots or restart budgets.
const result = template.templateId === "paperclip.cognee-cloud"
? await invoke()
: await runtimeSupervisor.useConnectionSlot(
{
companyId: session.companyId,
applicationId: tool.applicationId ?? null,
@@ -6286,18 +6326,11 @@ export function createToolGatewayService(
},
async (handle) => {
handle.appendLog("stdout", `calling ${entry.toolName}`);
return callLocalStdioMcp({
connection,
entry,
template,
env,
parameters,
timeoutMs: ms,
});
return invoke();
},
);
return {
result: normalizeMcpToolResult(result, "local_stdio", true),
result: normalizeMcpToolResult(result, template.templateId === "paperclip.cognee-cloud" ? "cognee_cloud" : "local_stdio", template.templateId !== "paperclip.cognee-cloud"),
};
}
@@ -7111,6 +7144,7 @@ export function createToolGatewayService(
args.tool,
args.parameters,
executionTimeoutMs,
args.timeoutMs === undefined,
)
: null;
if (!connectedMcpExecution) {
@@ -7130,6 +7164,11 @@ export function createToolGatewayService(
sensitiveMode: "redact",
promptInjectionMode: "block",
});
const providerResult = asRecord(resultValidation.value);
if (providerResult?.error) {
throw new ToolGatewayHttpError(502, String(providerResult.content || providerResult.error),
"tool_error", { execution: connectedMcpExecution.execution });
}
await db
.update(toolInvocations)
.set({
@@ -10397,6 +10436,7 @@ export function createToolGatewayService(
tool,
effectiveParameters,
executionTimeoutMs,
input.timeoutMs === undefined,
)
: null;
const result = connectedMcpExecution
@@ -10427,6 +10467,17 @@ export function createToolGatewayService(
promptInjectionMode: "block",
});
const completedAt = new Date();
const validatedMcpResult = connectedMcpExecution
? asRecord(resultValidation.value)
: null;
if (validatedMcpResult?.error) {
throw new ToolGatewayHttpError(
502,
String(validatedMcpResult.content || validatedMcpResult.error),
"tool_error",
{ execution: connectedMcpExecution?.execution },
);
}
await db
.update(toolInvocations)
.set({