mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use apps through Paperclip's MCP client. The client calls each provider's remote (Streamable HTTP) or local (stdio) MCP server. > - The client spoke only protocol 2025-06-18. It always did the `initialize` handshake and it sent client capabilities only in that handshake. > - MCP 2026-07-28 removes the handshake and sessions. Every request carries its version, capabilities and client identity in `_meta`. Servers that only speak 2026-07-28 reject the old requests, and they never see that Paperclip renders MCP Apps views. > - Public servers already speak it: DeepWiki and Context7 answer `server/discover` with 2026-07-28 today. > - This pull request makes the client negotiate the version per server. It speaks stateless MCP to 2026-07-28 servers and keeps the handshake for 2025-11-25 and older servers. > - The benefit is that new and old providers both work, and a tool call to a stateless server is one HTTP request with no handshake. ## Linked Issues or Issue Description Refs #21119 (MCP Apps host). This PR sends its MCP Apps capability to stateless servers too. **Subsystem affected** Server: the MCP client in `server/src/services/mcp-http.ts`, catalog discovery, the tool gateway (`tools/call`, context reads, stdio), and the remote MCP OAuth flow. **Problem or motivation** The client used protocol 2025-06-18 only. MCP 2026-07-28 makes MCP stateless: no `initialize`, no `Mcp-Session-Id`, per-request `_meta`, `server/discover`, `resultType` with multi round-trip requests (MRTR), cacheable lists, required `Mcp-Method`/`Mcp-Name` headers, and RFC 9207 `iss` validation. Servers that speak only 2026-07-28 cannot be used. Paperclip advertised MCP Apps support only in `initialize`, so stateless servers never saw it. **Proposed solution** Probe each server once with `server/discover`, pick the newest mutually supported version, and save it on the connection. Send stateless requests to modern servers and keep the handshake for legacy servers. Tool calls use the saved version and never probe. The saved version is checked again only when a request built from it is refused. **Alternatives considered** Inline negotiation (send each request in modern shape first and fall back on `400`) adds a failed request to every call to a legacy session server. Probing on every tool call adds a round trip before each tool runs. Saving the negotiated version keeps tool calls at one request. **Roadmap alignment** MCP protocol currency for the Apps and connections substrate. It follows the MCP Apps host work in #21119. **Additional context** Spec: https://modelcontextprotocol.io/specification/2026-07-28/changelog. Out of scope (separate work): the Tasks extension, Skills over MCP, `subscriptions/listen`, progress and cancellation, icons, enterprise-managed authorization. ## What Changed - `mcp-http.ts`: `negotiateMcpProtocolVersion` probes with `server/discover`. A `DiscoverResult` or a modern error (`-32020`/`-32021`/`-32022`) means a modern server. Anything else means a legacy server, which gets `initialize`. A `401`/`403` keeps the challenge for OAuth discovery. The era is remembered per connection and endpoint. - `mcpHttpRequestInit` builds every request. It always sends `Mcp-Method` and `Mcp-Name` (Base64 sentinel when unsafe). For modern versions it adds `_meta` (`protocolVersion`, `clientCapabilities` with `extensions["io.modelcontextprotocol/ui"]` and URL elicitation, `clientInfo`) and `Mcp-Param-*` headers from `x-mcp-header`. - Legacy `initialize` now requests 2025-11-25 and advertises the MCP Apps extension. - Catalog refresh saves `config.mcpProtocolVersion`. It drops tools with invalid `x-mcp-header` annotations. It reuses a fresh `tools/list` result (`ttlMs`, `cacheScope`). It probes again when the saved version is refused, and it negotiates again after a credential refresh. - `tools/call`: a saved modern version is called directly (no probe, no handshake). A modern rejection of a legacy-shaped call, or `-32022`, gets one retry with a negotiated version. The server rejected the first request before it ran, so the retry cannot repeat a side effect. A remembered legacy server that refuses `initialize` is probed again. - MRTR: `input_required` with URL requests becomes the existing provider link flow (`provider_interaction_required`). The next identical call sends `requestState` and `inputResponses`. Form, sampling and roots requests stop with `provider_input_required` and a plain message. A missing `resultType` means `complete`. - Context reads (`resources/*`, `prompts/*`) use the saved version, cache fresh results, and stop on `input_required`. The error code is kept, so resource not found (`-32602` or `-32002`) is visible. - stdio: probe with `server/discover` (2 s limit). Restart a server that exits on the probe. Send `_meta` to modern servers. - OAuth: refuse a callback without `iss` when the server advertises `authorization_response_iss_parameter_supported`. Check `iss` before acting on a provider error. Send `application_type: "native"` for localhost callbacks and `web` otherwise. Issuer-bound clients and the CIMD-first order already existed. - Docs: `doc/connections/MCP-PROTOCOL-VERSIONS.md`, linked from `doc/connections/README.md`. ## Verification - New suite `server/src/__tests__/mcp-protocol-versions.test.ts` (19 tests) uses a fake 2026-07-28 server and a fake legacy session server. It covers discovery, `_meta`, headers, version fallback, `-32022`, `resultType`, MRTR link and retry, form stop, cache TTL, legacy flow, and recovery when a saved legacy server moves to 2026-07-28. Embedded Postgres runs the end-to-end cases. - New OAuth tests in `generic-mcp-connection.test.ts`: `iss` required when advertised, `iss` checked on provider errors, `native` for localhost, and a stateless server listed again after a revoked token. - Red/green: with the master service code, all 21 new protocol and OAuth tests fail. With this change they pass. The token-refresh regression test fails without its fix and passes with it. - Existing suites: 12 touched files, 1088 tests pass. `tsc --noEmit` passes for `server`. Updated expectations count the one-time `server/discover` probe, and the Calendly DCR test now expects `native` for its localhost callback. - `pnpm verify` exits 2 (a doc is a global CI input), so CI supplies the broad coverage. - Live check with the changed client, without credentials: - DeepWiki (`mcp.deepwiki.com/mcp`): discover 200 → 2026-07-28, no session, `tools/list` 200 (3 tools). - Context7 (`mcp.context7.com/mcp`): discover 200 → 2026-07-28, no session, `tools/list` 200 (2 tools). - GitMCP (`gitmcp.io/docs`): discover 400 → `initialize` (2025-03-26) → session → `tools/list` 200 (5 tools). - Circleback (`circleback.ai/api/mcp`): discover 401 with its `WWW-Authenticate` challenge kept for sign-in. ## Risks - A legacy server that is not saved as session-required gets one extra request (`server/discover`) the first time it is refreshed. Then the version is saved. Saved session-required connections are not probed. - DCR from a localhost callback now registers a `native` client. This is what the spec asks for. Existing registrations are reused. - An authorization server that advertises `iss` support but does not send `iss` now fails sign-in with a clear message. The spec requires this. - MRTR answers are kept in memory for 30 minutes. After a restart the server asks again, and the user sees the link again. - No schema change. `config.mcpProtocolVersion` is a new key in the existing JSON config. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code with tool use (shell, file edits, web fetch of the MCP spec), extended reasoning. ## 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 - [ ] 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>
298 lines
24 KiB
TypeScript
298 lines
24 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import { agents, heartbeatRuns, issues, toolCatalogEntries, toolConnectionInstalls, toolInvocations, companies, companyMemberships, instanceSettings, createDb, toolConnections, toolPolicies, toolProfileEntries } from "@paperclipai/db";
|
|
import { eq } from "drizzle-orm";
|
|
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { toolAccessService } from "../services/tool-access.js";
|
|
import { createToolGatewayService } from "../services/tool-gateway.js";
|
|
import { instanceSettingsService, normalizeExperimentalSettings } from "../services/instance-settings.js";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { toolAccessRoutes } from "../routes/tool-access.js";
|
|
const actor = { actorType: "user" as const, actorId: "mcp-test-user", actorSource: "local_implicit" as const };
|
|
const tool = (name: string) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } });
|
|
describe("remote connector lifecycle", () => {
|
|
let fixture: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
let keyDir: string;
|
|
beforeAll(async () => {
|
|
keyDir = await mkdtemp(join(tmpdir(), "mcp-connector-secrets-"));
|
|
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key"));
|
|
fixture = await startEmbeddedPostgresTestDatabase("mcp-connectors-test-");
|
|
db = createDb(fixture.connectionString);
|
|
});
|
|
afterAll(async () => { await fixture?.cleanup(); vi.unstubAllEnvs(); if (keyDir) await rm(keyDir, { recursive: true, force: true }); });
|
|
async function company() {
|
|
const [row] = await db.insert(companies).values({ name: `MCP ${randomUUID()}`, issuePrefix: `M${randomUUID().slice(0, 5)}` }).returning();
|
|
await db.insert(companyMemberships).values({ companyId: row.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" });
|
|
return row;
|
|
}
|
|
function remoteFixture() {
|
|
const requests: { url: string; headers: Headers }[] = [];
|
|
let added = false;
|
|
let removed = false;
|
|
const service = toolAccessService(db, { deploymentMode: "local_trusted", deploymentExposure: "private",
|
|
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }],
|
|
remoteHttpRequest: async (url, init) => {
|
|
const body = JSON.parse(String(init.body)); const headers = new Headers(init.headers);
|
|
requests.push({ url, headers });
|
|
if (body.method === "initialize") return Response.json({ id: body.id, jsonrpc: "2.0", result: { protocolVersion: "2025-06-18", capabilities: {} } }, { headers: { "Mcp-Session-Id": "session" } });
|
|
expect(headers.get("mcp-session-id")).toBe("session");
|
|
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
|
|
expect(body.method).toBe("tools/list");
|
|
return Response.json({ id: body.id, jsonrpc: "2.0", result: body.params?.cursor
|
|
? { tools: [tool("ask"), ...(added ? [tool("new_tool")] : [])] }
|
|
: { tools: [tool("read"), ...(!removed ? [tool("off")] : [])], nextCursor: "page-two" } });
|
|
},
|
|
});
|
|
return { service, requests, add: () => { added = true; }, remove: () => { removed = true; }, restore: () => { removed = false; } };
|
|
}
|
|
it("advertises the initiating OAuth callback and preserves explicitly configured origins", async () => {
|
|
const org = await company();
|
|
const app = express();
|
|
app.use((req, _res, next) => { req.actor = { type: "board", userId: actor.actorId, source: "local_implicit", isInstanceAdmin: true }; next(); });
|
|
app.use("/api", toolAccessRoutes(db, { paperclipCloudConnector: null }));
|
|
|
|
const publicBaseUrlEnv = process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL;
|
|
const otherPublicUrlNames = ["BETTER_AUTH_URL", "BETTER_AUTH_BASE_URL", "PAPERCLIP_PUBLIC_URL", "PAPERCLIP_MANAGED_RUNTIME_PUBLIC_URL"] as const;
|
|
const otherPublicUrlEnv = Object.fromEntries(otherPublicUrlNames.map((name) => [name, process.env[name]]));
|
|
try {
|
|
for (const name of otherPublicUrlNames) process.env[name] = "";
|
|
process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = "https://paperclip.example.test";
|
|
const configured = await request(app).get(`/api/companies/${org.id}/tools/gallery`);
|
|
expect(configured.status).toBe(200);
|
|
expect(configured.body.oauthCallbackUrl).toBe("https://paperclip.example.test/api/tools/oauth/callback");
|
|
|
|
process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = "http://127.0.0.1:3105";
|
|
const configuredLoopback = await request(app).get(`/api/companies/${org.id}/tools/gallery`);
|
|
expect(configuredLoopback.status).toBe(200);
|
|
expect(configuredLoopback.body.oauthCallbackUrl).toBe("http://127.0.0.1:3105/api/tools/oauth/callback");
|
|
|
|
delete process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL;
|
|
const inferredLoopback = await request(app)
|
|
.get(`/api/companies/${org.id}/tools/gallery`)
|
|
.set("host", "127.0.0.1:3105");
|
|
expect(inferredLoopback.status).toBe(200);
|
|
expect(inferredLoopback.body.oauthCallbackUrl).toBe("http://localhost:3105/api/tools/oauth/callback");
|
|
|
|
const unsupported = await request(app)
|
|
.get(`/api/companies/${org.id}/tools/gallery`)
|
|
.set("host", "paperclip.internal.test");
|
|
expect(unsupported.status).toBe(200);
|
|
expect(unsupported.body).not.toHaveProperty("oauthCallbackUrl");
|
|
} finally {
|
|
if (publicBaseUrlEnv === undefined) delete process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL;
|
|
else process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL = publicBaseUrlEnv;
|
|
for (const name of otherPublicUrlNames) {
|
|
const value = otherPublicUrlEnv[name];
|
|
if (value === undefined) delete process.env[name];
|
|
else process.env[name] = value;
|
|
}
|
|
}
|
|
});
|
|
it.each([undefined, false])("allows all aggregator setup with stored setting %s", async (legacyValue) => {
|
|
await db.delete(instanceSettings);
|
|
if (legacyValue !== undefined) await db.insert(instanceSettings).values({ experimental: { enableMcpAggregators: legacyValue } });
|
|
expect(normalizeExperimentalSettings({ enableMcpAggregators: legacyValue }).enableMcpAggregators).toBe(true);
|
|
expect((await instanceSettingsService(db).getExperimental()).enableMcpAggregators).toBe(true);
|
|
const org = await company(); const remote = remoteFixture();
|
|
const app = express();
|
|
app.use((req, _res, next) => { req.actor = { type: "board", userId: actor.actorId, source: "local_implicit", isInstanceAdmin: true }; next(); });
|
|
app.use("/api", toolAccessRoutes(db, { paperclipCloudConnector: null }));
|
|
const gallery = await request(app).get(`/api/companies/${org.id}/tools/gallery`);
|
|
expect(gallery.status).toBe(200);
|
|
expect(gallery.body.apps.map((entry: { slug: string }) => entry.slug)).toEqual(expect.arrayContaining(["zapier", "arcade", "composio", "executor", "notion"]));
|
|
expect(gallery.body.apps.some((entry: { slug: string }) => entry.slug === "mem0")).toBe(false);
|
|
for (const [galleryKey, connectionMethodKey, link] of [
|
|
["zapier", "generated-url", "https://mcp.zapier.com/api/v1/connect?token=fixture-secret"],
|
|
["arcade", "mcp", "https://api.arcade.dev/mcp/fixture"],
|
|
["composio", "mcp", "https://connect.composio.dev/mcp"],
|
|
["executor", "mcp", "https://example.com/mcp"],
|
|
]) {
|
|
const connected = await remote.service.connectGalleryApp(org.id, { galleryKey, connectionMethodKey, link, authMode: "none" }, actor);
|
|
expect(connected.catalog).toHaveLength(3);
|
|
expect(connected.connectionId).toBeTruthy();
|
|
}
|
|
});
|
|
it.each([
|
|
["zapier", "generated-url", "https://mcp.zapier.com/api/v1/connect?token=fixture-secret"],
|
|
["composio", "mcp", "https://mcp.composio.dev/session/fixture?token=fixture-secret"],
|
|
])("%s vaults session URLs, paginates discovery, preserves Off/Ask during refresh and reconnect, and isolates companies", async (galleryKey, connectionMethodKey, link) => {
|
|
const org = await company(); const other = await company(); const remote = remoteFixture();
|
|
const input = { galleryKey, connectionMethodKey, link, authMode: "none" as const };
|
|
const connected = await remote.service.connectGalleryApp(org.id, input, actor);
|
|
expect(connected.catalog).toHaveLength(3);
|
|
expect(JSON.stringify(connected)).not.toContain("fixture-secret");
|
|
expect(remote.requests.every((r) => r.url.includes("token=fixture-secret"))).toBe(true);
|
|
const ids = Object.fromEntries(connected.catalog.map((entry) => [entry.toolName, entry.id]));
|
|
const finished = await remote.service.finishGalleryAppConnection(org.id, connected.connectionId, { enabledCatalogEntryIds: [ids.read, ids.ask], askFirstCatalogEntryIds: [ids.ask], access: "all_agents" }, actor);
|
|
remote.add();
|
|
const refreshed = await remote.service.refreshCatalog(connected.connectionId, actor, { enableAllByDefault: true });
|
|
const newId = refreshed.catalog.find((entry) => entry.toolName === "new_tool")!.id;
|
|
const entries = await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, finished.profile.id));
|
|
expect(entries.map((entry) => entry.catalogEntryId)).toEqual(expect.arrayContaining([ids.read, ids.ask, newId]));
|
|
expect(entries.map((entry) => entry.catalogEntryId)).not.toContain(ids.off);
|
|
await expect(remote.service.connectGalleryApp(other.id, { ...input, reconnectConnectionId: connected.connectionId }, actor)).rejects.toThrow("not found");
|
|
const reconnected = await remote.service.connectGalleryApp(org.id, { ...input, reconnectConnectionId: connected.connectionId }, actor);
|
|
const restored = await remote.service.finishGalleryAppConnection(org.id, connected.connectionId, { enabledCatalogEntryIds: reconnected.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: "all_agents" }, actor);
|
|
expect(restored.connection.status).toBe("active");
|
|
expect(restored.profileEntries.map((entry) => entry.catalogEntryId)).not.toContain(ids.off);
|
|
const policies = await db.select().from(toolPolicies).where(eq(toolPolicies.companyId, org.id));
|
|
expect(policies.some((policy) => policy.enabled && policy.config?.catalogEntryId === ids.ask)).toBe(true);
|
|
remote.remove();
|
|
const afterRemoval = await remote.service.refreshCatalog(connected.connectionId, actor);
|
|
expect(afterRemoval.catalog.find((entry) => entry.toolName === "off")?.status).not.toBe("active");
|
|
const [retired] = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.id, ids.off));
|
|
expect(retired.status).toBe("disabled"); // Check persisted discovery, not just this refresh response.
|
|
remote.restore();
|
|
const afterReturn = await remote.service.refreshCatalog(connected.connectionId, actor);
|
|
expect(afterReturn.catalog.find((entry) => entry.toolName === "off")?.status).toBe("active");
|
|
const retainedEntries = await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, finished.profile.id));
|
|
expect(retainedEntries.map((entry) => entry.catalogEntryId)).not.toContain(ids.off);
|
|
await remote.service.archiveConnection(connected.connectionId, org.id, actor);
|
|
const [removed] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
|
|
expect(removed.enabled).toBe(false);
|
|
expect(removed.status).toBe("archived");
|
|
});
|
|
it("renews expired discovery sessions and requires an explicit retry after an expired execution session", async () => {
|
|
const org = await company();
|
|
const [agent] = await db.insert(agents).values({ companyId: org.id, name: "Session tester", role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
|
|
let initialized = 0;
|
|
const expired = new Set<string>();
|
|
const calls: string[] = [];
|
|
const send = async (_url: string, init: RequestInit) => {
|
|
const body = JSON.parse(String(init.body));
|
|
if (body.method === "initialize") return Response.json({ id: body.id, result: { protocolVersion: "2025-06-18" } }, { headers: { "Mcp-Session-Id": `session-${++initialized}` } });
|
|
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
|
|
const session = new Headers(init.headers).get("mcp-session-id")!;
|
|
if (body.method === "tools/call") calls.push(session);
|
|
if (expired.has(session)) return new Response(null, { status: 404 });
|
|
return Response.json({ id: body.id, result: body.method === "tools/list" ? { tools: [tool("read")] } : { content: [{ type: "text", text: "ok" }] } });
|
|
};
|
|
const service = toolAccessService(db, { deploymentMode: "local_trusted", deploymentExposure: "private", remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], remoteHttpRequest: send });
|
|
const connected = await service.connectGalleryApp(org.id, { galleryKey: "arcade", connectionMethodKey: "mcp", link: "https://api.arcade.dev/mcp/expiration", authMode: "none" }, actor);
|
|
const beforeRefresh = initialized;
|
|
expired.add(`session-${initialized}`);
|
|
expect((await service.refreshCatalog(connected.connectionId, actor)).catalog).toHaveLength(1);
|
|
expect(initialized).toBe(beforeRefresh + 1);
|
|
await service.finishGalleryAppConnection(org.id, connected.connectionId, { enabledCatalogEntryIds: connected.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: "all_agents" }, actor);
|
|
const gateway = createToolGatewayService(db, { deploymentMode: "local_trusted", deploymentExposure: "private", remoteHttpRequest: send });
|
|
const call = () => gateway.executeTestCall({ companyId: org.id, connectionId: connected.connectionId, agentId: agent.id, userId: actor.actorId, toolName: "read", parameters: {} });
|
|
expect(await call()).toMatchObject({ decision: "allowed", result: { data: { isError: false } } });
|
|
const executionSession = calls[0];
|
|
expired.add(executionSession);
|
|
const failed = await call();
|
|
expect(failed).toMatchObject({ error: { reasonCode: "mcp_remote_status" } });
|
|
expect(calls).toEqual([executionSession, executionSession]);
|
|
expect(await call()).toMatchObject({ decision: "allowed", result: { data: { isError: false } } });
|
|
expect(calls).toHaveLength(3);
|
|
expect(calls[2]).not.toBe(executionSession);
|
|
});
|
|
it("saves a vaulted draft without contacting the provider and resumes with custom headers", async () => {
|
|
const org = await company(); const remote = remoteFixture();
|
|
const input = { galleryKey: "arcade", connectionMethodKey: "mcp", link: "https://api.arcade.dev/mcp/fixture", authMode: "bearer" as const };
|
|
const draft = await remote.service.connectGalleryApp(org.id, { ...input, saveDraft: true, credentialValues: { "credentials.authorization": "fixture-key", "headers.Arcade-User-ID": "test-user" } }, actor);
|
|
expect(remote.requests).toHaveLength(0);
|
|
expect(JSON.stringify(draft)).not.toContain("fixture-key");
|
|
const connected = await remote.service.connectGalleryApp(org.id, { ...input, resumeConnectionId: draft.connectionId }, actor);
|
|
expect(connected.catalog).toHaveLength(3);
|
|
expect(remote.requests.every((request) => request.headers.get("authorization") === "Bearer fixture-key" && request.headers.get("arcade-user-id") === "test-user")).toBe(true);
|
|
});
|
|
it("does not widen an empty agent selection after an OAuth callback or reconnect", async () => {
|
|
const org = await company();
|
|
const endpoint = "https://api.arcade.dev/mcp/fixture-oauth";
|
|
const send = async (url: string, init: RequestInit) => {
|
|
if (url.includes(".well-known/oauth-protected-resource")) return Response.json({ resource: endpoint, authorization_servers: ["https://auth.arcade.dev"] });
|
|
if (url.includes(".well-known/")) return Response.json({ issuer: "https://auth.arcade.dev", authorization_endpoint: "https://auth.arcade.dev/authorize", token_endpoint: "https://auth.arcade.dev/token", response_types_supported: ["code"], code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"] });
|
|
if (url === "https://auth.arcade.dev/token") return Response.json({ access_token: "fixture-access", token_type: "Bearer", expires_in: 3600 });
|
|
if (url !== endpoint) throw new Error(`Unexpected fixture URL: ${url}`);
|
|
if (!new Headers(init.headers).has("authorization")) return new Response(null, { status: 401, headers: { "WWW-Authenticate": 'Bearer resource_metadata="https://api.arcade.dev/.well-known/oauth-protected-resource"' } });
|
|
const body = JSON.parse(String(init.body));
|
|
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
|
|
return Response.json({ id: body.id, result: body.method === "initialize" ? { protocolVersion: "2025-06-18" } : { tools: [tool("read")] } });
|
|
};
|
|
const service = toolAccessService(db, { deploymentMode: "local_trusted", deploymentExposure: "private", remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], remoteHttpRequest: send });
|
|
const input = { galleryKey: "arcade", connectionMethodKey: "mcp", link: endpoint, authMode: "auto" as const, oauthClient: { clientId: "fixture-client" } };
|
|
const connected = await service.connectGalleryApp(org.id, input, actor);
|
|
const callback = async () => {
|
|
const redirectUri = "http://127.0.0.1:3116/api/tools/oauth/callback";
|
|
const started = await service.startOAuth(org.id, connected.connectionId, { redirectUri, actor });
|
|
return service.completeOAuthCallback({ state: new URL(started.authorizationUrl).searchParams.get("state")!, code: "fixture-code", redirectUri, actor });
|
|
};
|
|
await service.putConnectionInstalls(connected.connectionId, { installs: [] }, actor);
|
|
const first = await callback();
|
|
expect(first.connection.status).toBe("active");
|
|
expect((await service.listConnectionInstalls(connected.connectionId))).toHaveLength(0);
|
|
await service.connectGalleryApp(org.id, { ...input, reconnectConnectionId: connected.connectionId }, actor);
|
|
await callback();
|
|
expect((await service.listConnectionInstalls(connected.connectionId))).toHaveLength(0);
|
|
});
|
|
it("enforces agent and action permissions before dispatch, and preserves provider resume after Paperclip approval", async () => {
|
|
const org = await company();
|
|
const [allowed, denied] = await db.insert(agents).values(["Allowed", "Denied"].map((name) => ({ companyId: org.id, name, role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }))).returning();
|
|
const calls: { name: string; arguments: unknown; session: string | null }[] = [];
|
|
const send = async (_url: string, init: RequestInit) => {
|
|
const body = JSON.parse(String(init.body));
|
|
if (body.method === "initialize") return Response.json({ id: body.id, result: { protocolVersion: "2025-06-18" } }, { headers: { "Mcp-Session-Id": "execution-session" } });
|
|
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
|
|
if (body.method === "server/discover") return Response.json({ id: body.id, error: { code: -32601, message: "Method not found" } }, { status: 404 });
|
|
if (body.method === "tools/list") return Response.json({ id: body.id, result: { tools: [tool("execute"), tool("resume"), tool("off")] } });
|
|
calls.push({ ...body.params, session: new Headers(init.headers).get("mcp-session-id") });
|
|
return Response.json({ id: body.id, result: { structuredContent: body.params.name === "execute"
|
|
? { status: "waiting_for_interaction", executionId: "fixture-execution", interaction: { kind: "form", message: "Approve read?", requestedSchema: { type: "object", properties: {} } } }
|
|
: { ok: true, resumed: body.params.arguments.executionId }, content: [] } });
|
|
};
|
|
const service = toolAccessService(db, { deploymentMode: "local_trusted", deploymentExposure: "private", remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], remoteHttpRequest: send });
|
|
const connection = await service.connectGalleryApp(org.id, { galleryKey: "executor", connectionMethodKey: "mcp", link: "https://executor.sh/test/mcp", authMode: "none" }, actor);
|
|
const ids = Object.fromEntries(connection.catalog.map((entry) => [entry.toolName, entry.id]));
|
|
await service.finishGalleryAppConnection(org.id, connection.connectionId, { enabledCatalogEntryIds: [ids.execute, ids.resume], askFirstCatalogEntryIds: [ids.execute], access: { agentIds: [allowed.id] } }, actor);
|
|
const gateway = createToolGatewayService(db, { deploymentMode: "local_trusted", deploymentExposure: "private", remoteHttpRequest: send, toolActionSigningSecret: "fixture-signing-key" });
|
|
const call = (agentId: string, toolName: string, parameters: Record<string, unknown> = {}) => gateway.executeTestCall({ companyId: org.id, connectionId: connection.connectionId, agentId, userId: actor.actorId, toolName, parameters });
|
|
expect((await call(denied.id, "execute")).decision).toBe("off");
|
|
expect((await call(allowed.id, "off")).decision).toBe("off");
|
|
expect(calls).toHaveLength(0);
|
|
const asked = await call(allowed.id, "execute");
|
|
expect(asked.decision).toBe("ask_first");
|
|
expect(calls).toHaveLength(0);
|
|
if (!("actionRequestId" in asked)) throw new Error("Missing approval request");
|
|
await gateway.approveActionRequest({ companyId: org.id, actionRequestId: asked.actionRequestId!, actor: { userId: actor.actorId } });
|
|
const status = await gateway.getTestCallStatus({ companyId: org.id, connectionId: connection.connectionId, actionRequestId: asked.actionRequestId! });
|
|
expect(status.phase).toBe("done");
|
|
expect(status.upstreamPending).toMatchObject({ executionId: "fixture-execution", resumeTool: "resume" });
|
|
const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, asked.invocationId));
|
|
expect(invocation.resultSummary?.summary).toContain("fixture-execution");
|
|
const resumed = await call(allowed.id, "resume", { executionId: status.upstreamPending!.executionId, action: "accept", content: "{}" });
|
|
expect(resumed.decision).toBe("allowed");
|
|
expect(calls.map((call) => call.name)).toEqual(["execute", "resume"]);
|
|
expect(calls.every((call) => call.session === "execution-session")).toBe(true);
|
|
const [issue] = await db.insert(issues).values({ companyId: org.id, title: "Provider approval", status: "in_progress", assigneeAgentId: allowed.id }).returning();
|
|
const [run] = await db.insert(heartbeatRuns).values({ companyId: org.id, agentId: allowed.id, invocationSource: "assignment", status: "running", contextSnapshot: { issueId: issue.id } }).returning();
|
|
const session = await gateway.createSession({ companyId: org.id, agentId: allowed.id, runId: run.id });
|
|
const execute = (await gateway.listToolsForSession(session.token)).find((entry) => entry.upstreamToolName === "execute")!;
|
|
expect(execute).toBeDefined();
|
|
let approvalId = "";
|
|
try { await gateway.executeTool({ sessionToken: session.token, tool: execute.name, parameters: {} }); }
|
|
catch (error) {
|
|
expect(error).toMatchObject({ reasonCode: "approval_required" });
|
|
approvalId = (error as { details: { actionRequestId: string } }).details.actionRequestId;
|
|
}
|
|
expect(approvalId).not.toBe("");
|
|
await gateway.approveActionRequest({ companyId: org.id, actionRequestId: approvalId, actor: { userId: actor.actorId } });
|
|
await expect(gateway.executeTool({ sessionToken: session.token, tool: execute.name, parameters: {} })).rejects.toMatchObject({
|
|
reasonCode: "provider_interaction_required", details: { upstreamPending: { executionId: "fixture-execution" } },
|
|
});
|
|
expect(calls).toHaveLength(3); // Retrying the approved action did not start another execution.
|
|
await service.finishGalleryAppConnection(org.id, connection.connectionId, { enabledCatalogEntryIds: [ids.execute, ids.resume], askFirstCatalogEntryIds: [ids.execute], access: { agentIds: [] } }, actor);
|
|
expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.connectionId))).toHaveLength(0);
|
|
expect((await call(allowed.id, "execute")).decision).toBe("off");
|
|
expect((await gateway.listToolsForSession(session.token)).filter((entry) => entry.connectionId === connection.connectionId)).toHaveLength(0);
|
|
await service.archiveConnection(connection.connectionId, org.id, actor);
|
|
await expect(call(allowed.id, "resume")).rejects.toThrow("not found");
|
|
expect(calls).toHaveLength(3);
|
|
});
|
|
|
|
});
|