feat(connections): name and guide connections to another Paperclip instance (#22018)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each Paperclip instance serves an assistant connection (MCP) at
`/mcp/paperclip`, and any instance can connect a remote MCP server by
its address
> - So one instance's agents can file and follow tasks on another
instance, for example a colleague's
> - But the other instance's tools look like the agent's own Paperclip
tools: same product, similar names, and the connection prefix was a
generic internal link key
> - An agent can then file local work on someone else's instance, or the
reverse
> - This pull request recognizes a Paperclip address, names the
connection and tool prefix after that instance, adds agent instructions,
and refuses a connection to the same instance
> - The benefit is that agents can tell their own Paperclip from a
connected one

## Linked Issues or Issue Description

**Subsystem affected**

Connections: "Connect your own MCP server" (generic remote MCP) and the
tool gateway names that agents see.

**Problem or motivation**

When instance A connects instance B through `/mcp/paperclip`, A's agents
get B's `paperclip_create_task` and other tools. The tool prefix came
from an internal key (`app-gallery🔗<uuid>`), so native runners saw
`app_mcp_app_gallery_link_paperclip_create_task_…`. Nothing told the
agent that the tools act on a different instance. An agent could send
internal work to another organization by mistake.

**Proposed solution**

Recognize an address whose path is `/mcp/paperclip`. Use only the typed
address, never data from the remote server. Name the connection after
the host (`acme Paperclip`). Use that name as the tool prefix for these
connections only. Add default agent instructions. Refuse the instance's
own address with `paperclip_self_connection` (422).

**Alternatives considered**

Read the company name from the remote `paperclip_connection` tool. This
needs an extra authenticated call during setup, and it puts
remote-controlled text in names and instructions. The host is enough to
identify the stack. Require approval for each write. We rejected this:
actions start on, the same as other connections.

**Roadmap alignment**

Supports instance-to-instance work through existing MCP connections. It
adds no new transport.

## What Changed

- `packages/shared/src/paperclip-peer.ts`: detect a Paperclip MCP
address, derive a label and name, compare with own origins (loopback
hosts on the same port are equal), and build default agent instructions.
- `server/src/services/tool-access.ts`: default name and default agent
instructions for a new Paperclip connection. Instructions that the
person supplies are kept.
- `server/src/routes/tool-access.ts`: refuse the instance's own address
before any network request.
- `server/src/services/tool-gateway.ts`: use the prefix recorded on a
Paperclip connection (`paperclipPeerToolNamespace`, derived from its
address at creation). Renames never change it. Other connections, and
Paperclip connections made before this change, keep their current tool
names.
- `ui/src/pages/apps/generic-mcp-connect.ts`: same default name in the
setup flow.
- `doc/connections/GENERIC-REMOTE-MCP.md`: new section "Connecting
another Paperclip instance".

## Verification

- `packages/shared`: `npx vitest run src/paperclip-peer.test.ts`, 20
passed.
- `server`: `npx vitest run
src/__tests__/generic-mcp-connection.test.ts`, 98 passed. The naming,
instructions, self-connection and tool-prefix tests fail on the base
revision and pass with this change (red/green).
- `ui`: `npx vitest run src/pages/apps/generic-mcp-connect.test.ts`, 29
passed.
- `tsc --noEmit` passes for `packages/shared` and `server`.
- Live check with two local instances. Instance B was in authenticated
mode on port 3201 with assistant connections on. Instance A was on port
3202.
- A connected to `http://localhost:3201/mcp/paperclip`. The name was
`localhost-3201 Paperclip`. A registered with B by dynamic client
registration and asked for read, write, configure and offline access.
- B's consent page showed "Connect Paperclip localhost-3202 to
Paperclip". After approval, A had all 37 tools active, writes included.
- From A, `paperclip_connection` returned B's company.
`paperclip_create_task` created `ACM-1` on B.
- An agent session on A listed
`mcp.localhost-3201-paperclip-…:paperclip-create-task` (runner name
`app_mcp_localhost_3201_p_paperclip_create_task_…`). Before the gateway
change, the name was `app_mcp_app_gallery_link_paperclip_connection_…`.
The run received the connection instructions.
- Connecting A to `http://localhost:3202/mcp/paperclip` returned 422
`paperclip_self_connection`.

## Risks

- Low risk. Only connections whose address path is exactly
`/mcp/paperclip` change. Other connections keep their names,
instructions and tool names.
- A Paperclip connection created before this change keeps its original
tool names, because only connections that record
`paperclipPeerToolNamespace` at creation get the new prefix. Saved exact
tool-name rules and pending approvals for those connections keep
matching. They also get no default instructions; people can add them.
- Native runners keep only 20 characters of the namespace (`mcp_` uses
4), so long host labels are cut. The tool part stays complete.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, browser pane).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-17 11:41:13 -06:00
1 parent 1d2b669e7a
commit b1efe32c60
13 files changed
+551 -18

No files matched your search

+31
View File
@@ -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-<id>: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
+9
View File
@@ -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,
@@ -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")!;
}
});
+115
View File
@@ -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<string | null | undefined>): 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))!;
}
@@ -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<string, unknown> };
/** 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<string, unknown>;
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&region=us`;
const publicUrl = `${MCP_URL}?region=us`;
+27 -1
View File
@@ -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") {
+59 -5
View File
@@ -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,
@@ -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 }];
});
+29 -3
View File
@@ -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<string, unknown> | 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<Map<string, number>>(
@@ -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",
+9 -2
View File
@@ -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
</p> : null}
{connection.config?.sourceTemplateKey !== "composio" && isRemoteMcpConnectorMethod(connection.config?.sourceTemplateKey, connection.config?.connectionMethodKey) && <p className="text-sm text-muted-foreground">Paperclip controls access to the tools listed here. App and action permissions inside these tools are managed in {baseAppName}.</p>}
<PermissionsPanel
afterAgentAccess={<>{logoEntry?.agentInstructions && <ConnectionInstructionsSettings key={connection.id} connection={connection} provider={logoEntry.name} template={logoEntry.agentInstructions} canConfigure={grantsQuery.data?.capabilities?.canConfigure ?? false} />}{renderAgentSettings?.(connection)}</>}
afterAgentAccess={<>{instructionsTemplate && <ConnectionInstructionsSettings key={connection.id} connection={connection} provider={instructionsTemplate.provider} template={instructionsTemplate.template} canConfigure={grantsQuery.data?.capabilities?.canConfigure ?? false} />}{renderAgentSettings?.(connection)}</>}
actions={actionsContent}
connectionId={connectionId}
capabilities={grantsQuery.data?.capabilities}
@@ -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", () => {
+3 -1
View File
@@ -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\./, "");