diff --git a/doc/connections/GENERIC-REMOTE-MCP.md b/doc/connections/GENERIC-REMOTE-MCP.md index 91a4ee3fd90..92fd6e805a4 100644 --- a/doc/connections/GENERIC-REMOTE-MCP.md +++ b/doc/connections/GENERIC-REMOTE-MCP.md @@ -79,6 +79,37 @@ Optional assigned apps do not emit run-start connection warnings, including unavailable shared apps. Their health state and reconnect controls remain in Apps. An unrelated run does not need to act on that state. +### Connecting another Paperclip instance + +Every Paperclip serves its assistant connection at `/mcp/paperclip` (see +[Public Paperclip MCP connection](../public-mcp.md)). Pasting that address +connects your agents to another instance — for example a colleague's — so they +can file and follow tasks there. Paperclip recognizes the address and, using +only the address you typed (nothing the other server says): + +- names the connection after that instance with its distinctive part first — + `acme Paperclip` for `acme.paperclip.app`, `localhost-3101 Paperclip` for a + local instance — and prefixes its tools with the same host-derived label, + so agents see + `mcp.acme-paperclip-:paperclip-create-task` (native runners: + `app_mcp_acme_paperclip_…_paperclip_create_task_…`), never a bare + `create_task` that looks like their own. Other address-based connections + keep their existing tool names. Setup records the prefix on the connection + (`paperclipPeerToolNamespace`) when it is created, so renaming or + reconnecting never changes tool names that saved tool-name rules, agents or + pending approvals refer to. Paperclip connections created before this keep + their original names; +- adds agent instructions (template `paperclip.peer`, editable and + resettable under **Agent instructions** on the connection's Permissions page) + saying these tools act on a different + Paperclip, that agents keep using their own Paperclip tools for their own + work, and that links from the other instance must be quoted in full; +- refuses the address of this same instance (`paperclip_self_connection`, + 422), because its tools are already built in. + +Actions start on, as for any other connection. A name or instructions you +supply yourself are kept. + ### Slack app access If Slack reports that MCP access is disabled for the app, ask the Slack app diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 793b9067f01..cf49de3e1c9 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -388,6 +388,15 @@ export { type McpRemoteHeaderCheck, type McpRemoteHeaderRejection, } from "./mcp-remote-headers.js"; +export { + PAPERCLIP_PEER_MCP_PATH, + isSamePaperclipInstance, + PAPERCLIP_PEER_INSTRUCTIONS_TEMPLATE_ID, + paperclipPeerAgentInstructions, + paperclipPeerFromMcpUrl, + paperclipPeerInstructionTemplate, + type PaperclipPeer, +} from "./paperclip-peer.js"; export { checkOAuthEndpointUrl, isSafeOAuthEndpointUrl, diff --git a/packages/shared/src/paperclip-peer.test.ts b/packages/shared/src/paperclip-peer.test.ts new file mode 100644 index 00000000000..304c9db3bb8 --- /dev/null +++ b/packages/shared/src/paperclip-peer.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { connectionAgentInstructionsSchema } from "./connection-instructions.js"; +import { isSamePaperclipInstance, paperclipPeerAgentInstructions, paperclipPeerFromMcpUrl, paperclipPeerInstructionTemplate } from "./paperclip-peer.js"; + +describe("paperclipPeerFromMcpUrl", () => { + it.each([ + ["https://acme.paperclip.app/mcp/paperclip", "acme", "acme Paperclip"], + ["https://paperclip.staging.paperclip.app/mcp/paperclip/", "staging", "staging Paperclip"], + ["https://pc.example.com/mcp/paperclip", "pc", "pc Paperclip"], + ["https://example.com/mcp/paperclip", "example", "example Paperclip"], + ["http://localhost:3101/mcp/paperclip", "localhost-3101", "localhost-3101 Paperclip"], + ["http://127.0.0.1:3101/mcp/paperclip", "127-0-0-1-3101", "127-0-0-1-3101 Paperclip"], + ["https://paperclip.app/mcp/paperclip", "paperclip", "Paperclip paperclip.app"], + ])("names %s after the instance it reaches", (url, label, name) => { + expect(paperclipPeerFromMcpUrl(url)).toMatchObject({ label, name }); + }); + + it("derives a tool prefix from the address, with the distinctive part first", () => { + expect(paperclipPeerFromMcpUrl("https://acme.paperclip.app/mcp/paperclip")?.toolNamespace).toBe("acme-paperclip"); + expect(paperclipPeerFromMcpUrl("https://paperclip.app/mcp/paperclip")?.toolNamespace).toBe("paperclip"); + }); + + it.each([ + "https://acme.paperclip.app/mcp", + "https://acme.paperclip.app/mcp/paperclip/extra", + "https://mcp.example.com/sse", + "ftp://acme.paperclip.app/mcp/paperclip", + "not a url", + "", + null, + ])("ignores %s", (url) => { + expect(paperclipPeerFromMcpUrl(url)).toBeNull(); + }); +}); + +describe("isSamePaperclipInstance", () => { + const peer = (url: string) => paperclipPeerFromMcpUrl(url)!; + + it("matches the instance's own public origin", () => { + expect(isSamePaperclipInstance(peer("https://acme.paperclip.app/mcp/paperclip"), [null, "https://acme.paperclip.app"])).toBe(true); + }); + + it("treats loopback hostnames on the same port as the same instance", () => { + expect(isSamePaperclipInstance(peer("http://127.0.0.1:3100/mcp/paperclip"), ["http://localhost:3100"])).toBe(true); + }); + + it("keeps another local instance on a different port distinct", () => { + expect(isSamePaperclipInstance(peer("http://localhost:3101/mcp/paperclip"), ["http://localhost:3100"])).toBe(false); + }); + + it("keeps another hosted instance distinct", () => { + expect(isSamePaperclipInstance(peer("https://bob.paperclip.app/mcp/paperclip"), ["https://acme.paperclip.app", "not a url"])).toBe(false); + }); +}); + +describe("paperclipPeerAgentInstructions", () => { + it("names the other instance, steers own work back home, and fits the instruction limits", () => { + const instructions = paperclipPeerAgentInstructions(peer()); + expect(connectionAgentInstructionsSchema.parse(instructions)).toEqual(instructions); + expect(instructions.enabled).toBe(true); + expect(instructions.template).toEqual({ id: "paperclip.peer", version: 1 }); + expect(instructions.text).toBe(paperclipPeerInstructionTemplate(peer()).text); + expect(instructions.text).toContain("https://acme.paperclip.app"); + expect(instructions.text).toContain("not the Paperclip you work in"); + expect(instructions.text).toContain("keep using your own Paperclip tools"); + }); + + function peer() { + return paperclipPeerFromMcpUrl("https://acme.paperclip.app/mcp/paperclip")!; + } +}); diff --git a/packages/shared/src/paperclip-peer.ts b/packages/shared/src/paperclip-peer.ts new file mode 100644 index 00000000000..12d38951f28 --- /dev/null +++ b/packages/shared/src/paperclip-peer.ts @@ -0,0 +1,115 @@ +import { defaultConnectionAgentInstructions, type ConnectionAgentInstructions, type ConnectionInstructionTemplate } from "./connection-instructions.js"; + +/** + * Another Paperclip instance connected through "Connect your own MCP server". + * + * Every Paperclip serves its assistant connection at the same path. Recognizing + * that address lets setup name the connection after the instance it reaches and + * tell agents those tools act somewhere else. Agents already have their own + * Paperclip tools, so without this the two sets look alike: same names, same + * product in every description. + * + * Everything here is derived from the address the person typed. Nothing the + * remote server returns is used, so a remote instance cannot choose the name or + * the instructions agents read. + */ +export const PAPERCLIP_PEER_MCP_PATH = "/mcp/paperclip"; + +export interface PaperclipPeer { + /** `https://acme.paperclip.app` */ + origin: string; + /** `acme.paperclip.app`, with a port when one is present. */ + host: string; + /** Short distinctive part of the host: `acme`, `staging`, `localhost-3101`. */ + label: string; + /** Default connection name. The label comes first so it reads distinctively. */ + name: string; + /** Tool-name prefix agents see. Derived from the address, so renaming never changes it. */ + toolNamespace: string; +} + +const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]); +const GENERIC_HOST_LABELS = new Set(["www", "paperclip"]); + +function isIpAddress(hostname: string) { + return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("["); +} + +function hostLabel(url: URL): string { + const hostname = url.hostname.toLowerCase(); + if (LOOPBACK_HOSTNAMES.has(hostname) || isIpAddress(hostname) || !hostname.includes(".")) { + const base = hostname.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "paperclip"; + return url.port ? `${base}-${url.port}` : base; + } + const parts = hostname.split("."); + // Drop the registrable domain (approximated as the last two labels) and + // generic labels, so `acme.paperclip.app` becomes `acme` and + // `paperclip.staging.paperclip.app` becomes `staging`. + const subdomain = (parts.length >= 3 ? parts.slice(0, -2) : parts.slice(0, -1)) + .filter((part) => !GENERIC_HOST_LABELS.has(part)); + const chosen = subdomain.length > 0 ? subdomain : parts.slice(0, -1); + const label = chosen.join("-").replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, ""); + return label.slice(0, 40) || "paperclip"; +} + +/** The other Paperclip this MCP address points at, or null for any other server. */ +export function paperclipPeerFromMcpUrl(value: string | null | undefined): PaperclipPeer | null { + if (!value) return null; + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return null; + } + if (url.protocol !== "https:" && url.protocol !== "http:") return null; + if (url.pathname.replace(/\/+$/, "") !== PAPERCLIP_PEER_MCP_PATH) return null; + const label = hostLabel(url); + return { + origin: url.origin, + host: url.host, + label, + name: label === "paperclip" ? `Paperclip ${url.host}` : `${label} Paperclip`, + toolNamespace: label === "paperclip" ? "paperclip" : `${label}-paperclip`, + }; +} + +function loopbackEquivalent(url: URL) { + const hostname = url.hostname.toLowerCase(); + const port = url.port || (url.protocol === "https:" ? "443" : "80"); + return LOOPBACK_HOSTNAMES.has(hostname) ? `${url.protocol}//loopback:${port}` : `${url.protocol}//${url.host.toLowerCase()}`; +} + +/** True when the peer is this same instance, under any of its own origins. */ +export function isSamePaperclipInstance(peer: PaperclipPeer, ownOrigins: Array): boolean { + const target = loopbackEquivalent(new URL(peer.origin)); + return ownOrigins.some((origin) => { + if (!origin) return false; + try { + return loopbackEquivalent(new URL(origin)) === target; + } catch { + return false; + } + }); +} + +export const PAPERCLIP_PEER_INSTRUCTIONS_TEMPLATE_ID = "paperclip.peer"; + +/** Default guidance for a peer connection; the connection screen edits and resets against it. */ +export function paperclipPeerInstructionTemplate(peer: PaperclipPeer): ConnectionInstructionTemplate { + return { + id: PAPERCLIP_PEER_INSTRUCTIONS_TEMPLATE_ID, + version: 1, + text: [ + `These tools act on a different Paperclip instance at ${peer.origin}, not the Paperclip you work in.`, + "For your own tasks, comments and documents, keep using your own Paperclip tools.", + `Use these tools only when your task asks you to send, read or update work on ${peer.host}.`, + `Whatever you send there is visible to that instance's organization, so include only what the task asks you to share.`, + `Task IDs and links from ${peer.host} do not exist in your own Paperclip: quote the full ${peer.origin} links these tools return.`, + ].join(" "), + }; +} + +/** Standing guidance attached to a new peer connection. People can edit or turn it off. */ +export function paperclipPeerAgentInstructions(peer: PaperclipPeer): ConnectionAgentInstructions { + return defaultConnectionAgentInstructions(paperclipPeerInstructionTemplate(peer))!; +} diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index 194979bf038..dc099c7c0e2 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -54,6 +54,8 @@ import { instanceSettingsService } from "../services/instance-settings.js"; import * as instanceSettingsModule from "../services/instance-settings.js"; import { connectionIntentService } from "../services/connection-intents.js"; import { createToolGatewayService } from "../services/tool-gateway.js"; +import { assignedToolName } from "../services/native-runtime/assigned-mcp-tools.js"; +import { listCompanyProviderToolIcons } from "../services/tool-access/catalog/icons.js"; import { toolAccessPolicyService } from "../services/tool-access-policy.js"; import { toolAccessRoutes } from "../routes/tool-access.js"; import { errorHandler } from "../middleware/index.js"; @@ -131,6 +133,8 @@ type FixtureOptions = { registrationFailure?: { status: number; body: Record }; /** Extra provider-owned callbacks returned alongside the requested callback. */ registrationExtraRedirectUris?: string[]; + /** Serve the MCP endpoint at this address instead of `MCP_URL`. */ + mcpUrl?: string; }; type FixtureRequest = { @@ -193,7 +197,8 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) { const tokenResponses: { access_token: string; refresh_token: string }[] = []; const tools = options.tools ?? FIXTURE_TOOLS; const scopes = options.scopes ?? (options.notebookAccount ? ["notebook:read", "notebook:write", "notebook:share", "notebook:delete"] : null); - const resourceMetadataUrl = `${MCP_ORIGIN}/.well-known/oauth-protected-resource/mcp`; + const mcpUrl = options.mcpUrl ?? MCP_URL; + const resourceMetadataUrl = `${MCP_ORIGIN}/.well-known/oauth-protected-resource${new URL(mcpUrl).pathname}`; const authorizationServerMetadata = () => ({ issuer: ISSUER, @@ -220,7 +225,7 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) { : null; requests.push({ method, url: href, headers, body: parsedBody }); - if (href === MCP_URL && method === "POST") { + if (href === mcpUrl && method === "POST") { if (auth === "oauth" && headers.authorization !== `Bearer ${accessToken}`) { return unauthorizedMcpResponse(resourceMetadataUrl); } @@ -258,7 +263,7 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) { } if (href === resourceMetadataUrl) { - return jsonResponse({ resource: MCP_URL, authorization_servers: [ISSUER] }); + return jsonResponse({ resource: mcpUrl, authorization_servers: [ISSUER] }); } // RFC 8414 inserts the well-known segment before the issuer path; OIDC @@ -864,6 +869,182 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { expect(profiles).toEqual([]); }); + describe("another Paperclip instance", () => { + const PEER_MCP_URL = `${MCP_ORIGIN}/mcp/paperclip`; + + it("names the connection after the instance and tells agents it is a different Paperclip", async () => { + installMcpOAuthFixture({ auth: "public", mcpUrl: PEER_MCP_URL }); + const company = await createCompany(db); + const service = toolAccessService(db); + + const result = await service.connectGalleryApp(company.id, { link: PEER_MCP_URL }); + + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, result.connectionId)); + expect(connection!.name).toBe("8-8-8-8 Paperclip"); + expect(connection!.agentInstructions).toMatchObject({ enabled: true, template: { id: "paperclip.peer", version: 1 } }); + expect(connection!.agentInstructions!.text).toContain(`a different Paperclip instance at ${MCP_ORIGIN}`); + expect(connection!.agentInstructions!.text).toContain("keep using your own Paperclip tools"); + // Writes start on, the same as any other connection. + expect(result.suggestedDefaults).toMatchObject({ askFirstRiskLevels: [] }); + }); + + it("prefixes the agent's tool names with the other instance, not a generic link key", async () => { + const listAgentTools = async (link: string) => { + const company = await createCompany(db); + const service = toolAccessService(db); + const connected = await service.connectGalleryApp(company.id, { link }); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Sender", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); + await service.finishGalleryAppConnection(company.id, connected.connectionId, { + enabledCatalogEntryIds: connected.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [agent!.id] }, + }); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent!.id, invocationSource: "on_demand", status: "running" }).returning(); + const gateway = createToolGatewayService(db); + const list = async () => { + const session = await gateway.createSession({ companyId: company.id, agentId: agent!.id, runId: run!.id }); + return (await gateway.listToolsForSession(session.token)) + .filter((tool) => tool.connectionId === connected.connectionId) + .sort((a, b) => a.name.localeCompare(b.name)); + }; + return Object.assign(await list(), { list, service, companyId: company.id, connectionId: connected.connectionId }); + }; + + installMcpOAuthFixture({ auth: "public", mcpUrl: PEER_MCP_URL }); + const peerTools = await listAgentTools(PEER_MCP_URL); + expect(peerTools.map((tool) => tool.name)).toEqual([ + expect.stringMatching(/^mcp\.8-8-8-8-paperclip-[0-9a-f]+:create-insight$/), + expect.stringMatching(/^mcp\.8-8-8-8-paperclip-[0-9a-f]+:list-insights$/), + ]); + expect(assignedToolName(peerTools[0]!.name)).toMatch(/^app_mcp_8_8_8_8_papercli_create_insight_/); + + // Provider icons are keyed by the same gateway name, so the chat finds them. + const icons = [{ src: "https://cdn.example.com/peer.png", mimeType: "image/png" }]; + await db.update(toolCatalogEntries).set({ icons }).where(eq(toolCatalogEntries.connectionId, peerTools.connectionId)); + expect((await listCompanyProviderToolIcons(db, peerTools.companyId, [peerTools.connectionId])).map((entry) => entry.gatewayToolName).sort()) + .toEqual(peerTools.map((tool) => tool.name)); + + // Renaming the connection must not rename tools agents or approvals already hold. + await peerTools.service.updateConnection(peerTools.connectionId, { name: "Ops intake" }); + expect((await peerTools.list()).map((tool) => tool.name)).toEqual(peerTools.map((tool) => tool.name)); + + expect((await db.select().from(toolConnections).where(eq(toolConnections.id, peerTools.connectionId)))[0]!.config) + .toMatchObject({ paperclipPeerToolNamespace: "8-8-8-8-paperclip" }); + + // A peer connection made before the prefix existed keeps its original + // names, so saved tool-name rules and pending approvals still match it. + const [legacy] = await db.select().from(toolConnections).where(eq(toolConnections.id, peerTools.connectionId)); + const { paperclipPeerToolNamespace: _dropped, ...legacyConfig } = legacy!.config as Record; + await db.update(toolConnections).set({ config: legacyConfig }).where(eq(toolConnections.id, peerTools.connectionId)); + expect((await peerTools.list()).map((tool) => tool.name)).toEqual([ + expect.stringMatching(/^mcp\.app-gallery-link-/), + expect.stringMatching(/^mcp\.app-gallery-link-/), + ]); + + // Other address-based connections keep their existing names. + vi.restoreAllMocks(); + installMcpOAuthFixture({ auth: "public" }); + const otherTools = await listAgentTools(MCP_URL); + expect(otherTools.map((tool) => tool.name)).toEqual([ + expect.stringMatching(/^mcp\.app-gallery-link-/), + expect.stringMatching(/^mcp\.app-gallery-link-/), + ]); + }); + + it("never revives a removed connection for a different server that has the same name", async () => { + installMcpOAuthFixture({ auth: "public", mcpUrl: PEER_MCP_URL }); + const company = await createCompany(db); + const service = toolAccessService(db); + const peer = await service.connectGalleryApp(company.id, { link: PEER_MCP_URL, name: "Shared name" }); + await service.archiveConnection(peer.connectionId, company.id); + + vi.restoreAllMocks(); + installMcpOAuthFixture({ auth: "public" }); + const other = await service.connectGalleryApp(company.id, { link: MCP_URL, name: "Shared name" }); + + expect(other.connectionId).not.toBe(peer.connectionId); + expect(other.application.id).not.toBe(peer.application.id); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, other.connectionId)); + expect(connection!.agentInstructions).toBeNull(); + expect(connection!.config).not.toHaveProperty("paperclipPeerToolNamespace"); + + // The same server still gets its retained identity back. + await service.archiveConnection(other.connectionId, company.id); + const again = await service.connectGalleryApp(company.id, { link: MCP_URL, name: other.application.name }); + expect(again.application.id).toBe(other.application.id); + }); + + it("keeps instructions the person supplied instead of the default", async () => { + installMcpOAuthFixture({ auth: "public", mcpUrl: PEER_MCP_URL }); + const company = await createCompany(db); + const supplied = { enabled: false, text: "Only file bugs here." }; + + const result = await toolAccessService(db).connectGalleryApp(company.id, { link: PEER_MCP_URL, name: "Ops intake", agentInstructions: supplied }); + + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, result.connectionId)); + expect(connection).toMatchObject({ name: "Ops intake", agentInstructions: supplied }); + }); + + it("adds no instructions to an MCP server that is not Paperclip", async () => { + installMcpOAuthFixture({ auth: "public" }); + const company = await createCompany(db); + + const result = await toolAccessService(db).connectGalleryApp(company.id, { link: MCP_URL }); + + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, result.connectionId)); + expect(connection).toMatchObject({ name: "8.8.8.8/mcp", agentInstructions: null }); + }); + + it("refuses to connect this Paperclip to itself", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch"); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://127.0.0.1:3100"); + const company = await createCompany(db); + const app = createRouteApp(db, { deploymentMode: "local_trusted", deploymentExposure: "private" }); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ link: "http://localhost:3100/mcp/paperclip" }) + .expect(422); + + expect(response.body).toMatchObject({ details: { code: "paperclip_self_connection" } }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + }); + + it("recognizes this Paperclip by the port it actually listens on", async () => { + vi.spyOn(globalThis, "fetch"); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", ""); + vi.stubEnv("PAPERCLIP_AUTH_PUBLIC_BASE_URL", ""); + vi.stubEnv("BETTER_AUTH_URL", ""); + vi.stubEnv("BETTER_AUTH_BASE_URL", ""); + vi.stubEnv("PAPERCLIP_MANAGED_RUNTIME_PUBLIC_URL", ""); + // Startup moved this server off the requested port, which another instance holds. + vi.stubEnv("PORT", "3101"); + vi.stubEnv("PAPERCLIP_LISTEN_PORT", "3100"); + const company = await createCompany(db); + const app = createRouteApp(db, { deploymentMode: "local_trusted", deploymentExposure: "private" }); + const connect = (link: string) => request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .set("Host", "paperclip.internal.test") + .send({ link }); + + const self = await connect("http://localhost:3100/mcp/paperclip").expect(422); + expect(self.body).toMatchObject({ details: { code: "paperclip_self_connection" } }); + // The instance on the requested port is someone else, so it is not refused as self. + const other = await connect("http://localhost:3101/mcp/paperclip"); + expect(other.body?.details?.code).not.toBe("paperclip_self_connection"); + }); + + it("sends a Paperclip address entered under Executor to the generic connection", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch"); + const company = await createCompany(db); + + await expect(toolAccessService(db).connectGalleryApp(company.id, { + galleryKey: "executor", connectionMethodKey: "mcp", link: PEER_MCP_URL, authMode: "none", + })).rejects.toMatchObject({ status: 400, details: { code: "paperclip_peer_requires_generic_connection" } }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + }); + }); + it.each(["organization", "user"] as const)("vaults a credential-bearing MCP URL for %s and never returns or logs its token", async (grantKind) => { const secretUrl = `${MCP_URL}?token=zapier-secret®ion=us`; const publicUrl = `${MCP_URL}?region=us`; diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 2dfb2a8c7e9..71d4c3fe42b 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -1,5 +1,5 @@ import { isCrossSiteOAuthCallbackNavigation, oauthCallbackInterstitialHtml } from "../lib/oauth-browser-return.js"; -import { aiConnectionRouterPluginKey } from "@paperclipai/shared"; +import { aiConnectionRouterPluginKey, isSamePaperclipInstance, paperclipPeerFromMcpUrl } from "@paperclipai/shared"; import { aiConnectionRouterService } from "../services/ai-connection-router.js"; import { loadPluginAppCatalog } from "../services/plugin-app-catalog.js"; import { composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSchema, composioAppAccountSchema } from "@paperclipai/shared"; @@ -446,6 +446,31 @@ export function toolAccessRoutes( return null; } + // Agents already have this instance's tools built in. Connecting it to itself + // only adds a second copy under another name, which is the confusion the + // peer-connection naming exists to prevent. + function assertNotThisPaperclip(req: Request, link: unknown) { + const peer = typeof link === "string" ? paperclipPeerFromMcpUrl(link) : null; + if (!peer) return; + const requestHost = req.get("host")?.trim(); + const ownOrigins = [ + configuredPublicBaseUrl(), + options.authPublicBaseUrl, + process.env.PAPERCLIP_PUBLIC_URL, + trustedBrowserBaseUrl(req), + requestLoopbackBaseUrl(req), + requestHost ? `${req.protocol}://${requestHost}` : null, + // The port this server actually listens on; startup may move off PORT. + process.env.PAPERCLIP_LISTEN_PORT ? `http://localhost:${process.env.PAPERCLIP_LISTEN_PORT}` : null, + ]; + if (isSamePaperclipInstance(peer, ownOrigins)) { + throw unprocessable( + "That address is this Paperclip. Your agents already have its tools, so there is nothing to connect.", + { code: "paperclip_self_connection" }, + ); + } + } + function oauthRedirectUri(req: Request, forInitiation = false) { const baseUrl = configuredPublicBaseUrl() ?? trustedBrowserBaseUrl(req) @@ -975,6 +1000,7 @@ function connectorEnrollmentPrincipal(req: Request): string { : ORGANIZATION_GRANT_DENIAL_REASON, ); } + assertNotThisPaperclip(req, req.body.link); try { const result = await svc.connectGalleryApp(companyId, req.body, connectionRequestActor(req)); if (result.auth?.kind === "oauth") { diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 38a905d4b90..3f0752028e5 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -88,7 +88,7 @@ import { loadPluginAppCatalog, pluginAppCatalogFor } from "./plugin-app-catalog. import { notifyChatEndpointWork } from "./chat-work-notifications.js"; -import { defaultConnectionAgentInstructions } from "@paperclipai/shared"; +import { defaultConnectionAgentInstructions, paperclipPeerAgentInstructions, paperclipPeerFromMcpUrl } from "@paperclipai/shared"; import { isBrowserUseConnection } from "./browser-use-client.js"; @@ -1571,7 +1571,20 @@ export function toolAccessService( }; } + /** Origin and path of a pasted MCP address; query strings may carry credentials and are ignored. */ + function linkEndpoint(value: unknown): string | null { + if (typeof value !== "string" || !value.trim()) return null; + try { + const url = new URL(value.trim()); + return `${url.origin}${url.pathname.replace(/\/+$/, "")}`; + } catch { + return null; + } + } + function defaultLinkName(link: string): string { + const peer = paperclipPeerFromMcpUrl(link); + if (peer) return peer.name; try { const url = new URL(link); const host = url.host.replace(/^www\./, ""); @@ -1775,16 +1788,36 @@ export function toolAccessService( : null; const requestedSource = galleryEntry?.slug ?? (input.link ? "link" : null); + // A pasted address names its own server. Default names can repeat + // across hosts (two `acme Paperclip`s), so a removed link connection is + // revived only for the same endpoint; otherwise the new server would + // inherit another server's identity, instructions and tool prefix. + const sameLinkEndpoint = async (applicationId: string) => { + const requested = linkEndpoint(input.link); + if (!requested) return false; + const retained = await db + .select({ config: toolConnections.config }) + .from(toolConnections) + .where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.applicationId, applicationId))); + return retained.some((row) => linkEndpoint(asRecord(row.config).url) === requested); + }; if ( recoverableApplication && requestedSource && - recoverableSource === requestedSource + recoverableSource === requestedSource && + (requestedSource !== "link" || await sameLinkEndpoint(recoverableApplication.id)) ) { existingApplication = recoverableApplication; } } await assertConnectorConnectionSetupEnabled(requestedResumeConnection ?? {}, existingApplication?.applicationKey); + // Another Paperclip reached by address: tell agents those tools act on a + // different instance. Derived from the typed address, never from the server. + const paperclipPeer = galleryEntry ? null : paperclipPeerFromMcpUrl(input.link); + const newConnectionAgentInstructions = paperclipPeer + ? paperclipPeerAgentInstructions(paperclipPeer) + : defaultConnectionAgentInstructions(galleryEntry?.agentInstructions); const requestedName = input.name ?? existingApplication?.name ?? @@ -1819,6 +1852,14 @@ export function toolAccessService( input.reconnectConnectionId && requestedResumeConnection?.status !== "draft" && requestedResumeConnection?.config.sourceTemplateKey === galleryEntry?.slug, )); + if (galleryEntry && input.link && paperclipPeerFromMcpUrl(input.link)) { + // Another Paperclip needs its own name, instructions and tool prefix, + // which only the "Connect your own MCP server" path sets up. + throw badRequest( + `That is a Paperclip address. Connect it with "Connect your own MCP server" instead of ${galleryEntry.name}.`, + { code: "paperclip_peer_requires_generic_connection" }, + ); + } if (galleryEntry && input.link) { const acceptsProviderGeneratedUrl = method?.transport === "mcp_remote" && @@ -2214,7 +2255,20 @@ export function toolAccessService( } : {}), } - : { ...baseConfig, quarantineNewEntries: false, unverifiedServer: true }; + : { + ...baseConfig, + quarantineNewEntries: false, + unverifiedServer: true, + // Peer tool prefix, fixed when the identity is created. A retained + // identity keeps whatever it had, so tool names that saved rules and + // approvals refer to never change on reconnect or rename. + ...(() => { + const namespace = retainedConnection + ? asRecord(retainedConnection.config).paperclipPeerToolNamespace + : paperclipPeer?.toolNamespace; + return typeof namespace === "string" ? { paperclipPeerToolNamespace: namespace } : {}; + })(), + }; if (method && isPaperclipCloudConnectorStrategy(method.oauthStrategy)) { const connectorProfile = method.connectorProfile; const profile = managedConnectorProfile(connectorProfile); @@ -2575,7 +2629,7 @@ export function toolAccessService( agentInstructions: input.agentInstructions !== undefined ? input.agentInstructions : retainedConnection ? retainedConnection.agentInstructions - : defaultConnectionAgentInstructions(galleryEntry?.agentInstructions), + : newConnectionAgentInstructions, config, transportConfig: config, credentialRefs, @@ -2612,7 +2666,7 @@ export function toolAccessService( agentInstructions: input.agentInstructions !== undefined ? input.agentInstructions : retainedConnection ? retainedConnection.agentInstructions - : defaultConnectionAgentInstructions(galleryEntry?.agentInstructions), + : newConnectionAgentInstructions, config, transportConfig: config, credentialRefs, diff --git a/server/src/services/tool-access/catalog/icons.ts b/server/src/services/tool-access/catalog/icons.ts index ed0b6d97f0e..b523084cf8f 100644 --- a/server/src/services/tool-access/catalog/icons.ts +++ b/server/src/services/tool-access/catalog/icons.ts @@ -2,7 +2,7 @@ import { and, eq, inArray, isNotNull, ne } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { toolApplications, toolCatalogEntries, toolConnections } from "@paperclipai/db"; import { readMcpIcons, type ProviderToolIconEntry } from "@paperclipai/shared"; -import { shortStableId, slugSegment } from "../../tool-gateway.js"; +import { connectionToolNamespace, slugSegment } from "../../tool-gateway.js"; import { assignedToolName } from "../../native-runtime/assigned-mcp-tools.js"; /** Most icon entries returned per company. The chat only needs the tools that declare icons. */ @@ -21,6 +21,7 @@ export async function listCompanyProviderToolIcons(db: Db, companyId: string, co icons: toolCatalogEntries.icons, connectionId: toolConnections.id, connectionName: toolConnections.name, + connectionConfig: toolConnections.config, transport: toolConnections.transport, applicationKey: toolApplications.applicationKey, applicationName: toolApplications.name, @@ -40,7 +41,10 @@ export async function listCompanyProviderToolIcons(db: Db, companyId: string, co return rows.flatMap((row) => { const icons = readMcpIcons(row.icons); if (!icons) return []; - const namespace = `${row.transport === "rest_api" ? "app" : "mcp"}.${slugSegment(row.applicationKey ?? row.connectionName ?? row.applicationName, "mcp")}-${shortStableId(row.connectionId)}`; + const namespace = connectionToolNamespace({ + connectionId: row.connectionId, transport: row.transport, connectionName: row.connectionName, + config: row.connectionConfig, applicationKey: row.applicationKey, applicationName: row.applicationName, + }); const gatewayToolName = `${namespace}:${slugSegment(row.toolName, "tool")}`; return [{ gatewayToolName, nativeToolName: assignedToolName(gatewayToolName), icons }]; }); diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 5cbf7d9c426..fcffe0162a9 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1093,6 +1093,31 @@ export function shortStableId(id: string): string { return id.replace(/-/g, "").slice(0, 8); } +/** + * The `transport.namespace-id` part of a connected tool's gateway name. Every + * place that rebuilds a gateway tool name (listing, icons) must use this. + * + * Another Paperclip's tools share names with the agent's own, so they carry + * that instance's label. Setup records it when the connection is created; it + * never follows the editable name. Connections without it, including peers + * created before it existed, keep their original names so saved tool-name + * rules and pending approvals still match. + */ +export function connectionToolNamespace(input: { + connectionId: string; + transport: string; + connectionName: string | null; + config: Record | null | undefined; + applicationKey: string | null | undefined; + applicationName: string; +}): string { + const peerNamespace = input.config?.paperclipPeerToolNamespace; + const namespaceSource = typeof peerNamespace === "string" && peerNamespace + ? peerNamespace + : input.applicationKey ?? input.connectionName ?? input.applicationName; + return `${input.transport === "rest_api" ? "app" : "mcp"}.${slugSegment(namespaceSource, "mcp")}-${shortStableId(input.connectionId)}`; +} + function toolRequiresFormalApproval(tool: ToolGatewayDescriptor): boolean { return tool.risk === "destructive"; } @@ -1771,10 +1796,11 @@ export function createToolGatewayService( ); const baseNames = eligibleRows.map( ({ catalogEntry, connection, application }) => { - const applicationKey = application.applicationKey ?? null; - const connectionNamespace = `${slugSegment(applicationKey ?? connection.name ?? application.name, "mcp")}-${shortStableId(connection.id)}`; const toolSlug = slugSegment(catalogEntry.toolName, "tool"); - return `${connection.transport === "rest_api" ? "app" : "mcp"}.${connectionNamespace}:${toolSlug}`; + return `${connectionToolNamespace({ + connectionId: connection.id, transport: connection.transport, connectionName: connection.name, + config: connection.config, applicationKey: application.applicationKey, applicationName: application.name, + })}:${toolSlug}`; }, ); const baseNameCounts = baseNames.reduce>( diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 073d42d1a47..0089818585f 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "793b9067f01fd57e8e33e4abea87f828d90d861a", + "packages/shared/src/index.ts": "cf49de3e1c9d28a3a918ce6be44e0c1b7a349430", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -305,6 +305,8 @@ "packages/shared/src/oauth-endpoint-url.ts": "5ea73648dc5df103881e40e8ed920e38d901760a", "packages/shared/src/openrouter-attribution.test.ts": "ddc980f9d06fac708d02dcef8a8962e9887d6854", "packages/shared/src/openrouter-attribution.ts": "b77e887721cbf6bd882004f07df2405b6e58e52c", + "packages/shared/src/paperclip-peer.test.ts": "304c9db3bb82871834f4e8970d334cb21bb9de7a", + "packages/shared/src/paperclip-peer.ts": "12d38951f28bc4b492e8074f56279ec0da543ec3", "packages/shared/src/plugin-apps.test.ts": "5f6d2f7cd49085c8ead90647c4ee63c050a0fc46", "packages/shared/src/plugin-apps.ts": "59e63a673878e460d4fedebca576eef091dff9b6", "packages/shared/src/portability-fidelity.test.ts": "3cb1d7740cd016d8f2000cf400b87971c571e5ed", diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx index 4b047c38cee..155e9b7d902 100644 --- a/ui/src/pages/apps/AppDetail.tsx +++ b/ui/src/pages/apps/AppDetail.tsx @@ -1,6 +1,6 @@ import { AppNotFound, AppReadError } from "./app-detail/AppReadError"; import { AiConnectionPoolConnector } from "@/components/ai-connections/AiConnectionPoolConnector"; -import { aiConnectionRouterPluginKey, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection } from "@paperclipai/shared"; +import { aiConnectionRouterPluginKey, googleWorkspaceSelectedScopes, paperclipPeerFromMcpUrl, paperclipPeerInstructionTemplate, type GoogleWorkspaceServiceSelection } from "@paperclipai/shared"; import { ConnectionInstructionsSettings } from "@/features/connections/ConnectionInstructions"; import { HonchoWorkspaceSettings } from "@/features/connections/HonchoWorkspaceSettings"; import { BrowserUseSettingsPanel } from "./app-detail/BrowserUseSettingsPanel"; @@ -232,6 +232,13 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio () => galleryEntryFor((galleryQuery.data?.apps ?? []) as AppGalleryDisplayEntry[], connection, application), [galleryQuery.data, connection, application], ); + // Curated apps carry their own template. A connection to another Paperclip + // gets one derived from its address, so its default guidance stays editable. + const instructionsTemplate = useMemo(() => { + if (logoEntry?.agentInstructions) return { provider: logoEntry.name, template: logoEntry.agentInstructions }; + const peer = paperclipPeerFromMcpUrl(typeof connection?.config?.url === "string" ? connection.config.url : null); + return peer ? { provider: peer.host, template: paperclipPeerInstructionTemplate(peer) } : null; + }, [logoEntry, connection]); const brandKey = appApplicationSourceSlug(application) ?? appConnectionSourceSlug(connection) ?? (logoEntry ? appDefinitionSlug(logoEntry) : null); @@ -694,7 +701,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio

: null} {connection.config?.sourceTemplateKey !== "composio" && isRemoteMcpConnectorMethod(connection.config?.sourceTemplateKey, connection.config?.connectionMethodKey) &&

Paperclip controls access to the tools listed here. App and action permissions inside these tools are managed in {baseAppName}.

} {logoEntry?.agentInstructions && }{renderAgentSettings?.(connection)}} + afterAgentAccess={<>{instructionsTemplate && }{renderAgentSettings?.(connection)}} actions={actionsContent} connectionId={connectionId} capabilities={grantsQuery.data?.capabilities} diff --git a/ui/src/pages/apps/generic-mcp-connect.test.ts b/ui/src/pages/apps/generic-mcp-connect.test.ts index 0f41fc29963..101fe06fd51 100644 --- a/ui/src/pages/apps/generic-mcp-connect.test.ts +++ b/ui/src/pages/apps/generic-mcp-connect.test.ts @@ -73,6 +73,11 @@ describe("defaultGenericMcpName", () => { expect(defaultGenericMcpName("https://www.example.test/mcp?token=secret")) .toBe("example.test/mcp"); }); + + it("names another Paperclip after the instance it reaches, distinctive part first", () => { + expect(defaultGenericMcpName("https://acme.paperclip.app/mcp/paperclip")).toBe("acme Paperclip"); + expect(defaultGenericMcpName("http://localhost:3101/mcp/paperclip")).toBe("localhost-3101 Paperclip"); + }); }); describe("genericConnectGuidance", () => { diff --git a/ui/src/pages/apps/generic-mcp-connect.ts b/ui/src/pages/apps/generic-mcp-connect.ts index dc568fb3f55..88222e26c57 100644 --- a/ui/src/pages/apps/generic-mcp-connect.ts +++ b/ui/src/pages/apps/generic-mcp-connect.ts @@ -1,4 +1,4 @@ -import { checkMcpRemoteHeaderName, checkMcpRemoteHeaderValue, mcpRemoteHeaderRejectionMessage } from "@paperclipai/shared"; +import { checkMcpRemoteHeaderName, checkMcpRemoteHeaderValue, mcpRemoteHeaderRejectionMessage, paperclipPeerFromMcpUrl } from "@paperclipai/shared"; import type { GenericMcpAuthMode } from "@paperclipai/shared"; /** @@ -67,6 +67,8 @@ export function oauthCallbackUrlForBrowser( * excluded because remote MCP URLs can carry credentials there. */ export function defaultGenericMcpName(url: string): string | null { + const peer = paperclipPeerFromMcpUrl(url); + if (peer) return peer.name; try { const parsed = new URL(url); const host = parsed.host.replace(/^www\./, "");