mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
feat(mcp): host the MCP Skills extension for connected apps (#21219)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use connected apps through MCP. Paperclip already hosts MCP Apps views and speaks stateless MCP 2026-07-28. > - The MCP Skills extension (SEP-2640, Final) lets an app publish skills (instructions and files) next to its tools. Hugging Face already serves 25. > - Paperclip did not read them, so agents missed each app's own workflow guidance. > - Skills are a prompt-injection surface. The spec makes manifest binding, verification, origin tagging and approval revocation host requirements. > - This pull request makes Paperclip a Skills host: discover, review, verify, and deliver app skills to the agents that use the app. > - The benefit is that connected apps can teach agents their workflows, under board control. ## Linked Issues or Issue Description **Problem** Connected MCP servers can publish skills with the `io.modelcontextprotocol/skills` extension. Paperclip ignored them. A board could not see, review or approve them, and agents never received them. **Proposed solution** Implement the host side of SEP-2640. List skills during catalog refresh, record them per connection and company, bind board approval to the full file manifest, and load approved skills into agent runs with verified, lazily fetched content. **Why it matters** Apps ship workflow guidance with their tools. Without the extension, each team must copy that guidance into company skills by hand, and it goes stale. Refs #21119, Refs #21140 (the MCP Apps and stateless MCP client work this builds on). ## What Changed - **Client capability.** Every stateless request declares `io.modelcontextprotocol/skills`. Legacy handshake sessions do not. The capabilities that `server/discover` advertises are remembered beside the protocol era. - **Discovery.** Catalog refresh calls `skills/list` (paged) only when the server declared the extension. A listing inside its `ttlMs` is reused. A skills failure never fails the tool refresh. Nothing runs while a run starts. - **Schema.** New `tool_mcp_skills` (company, connection, skill URI; frontmatter, sorted manifest, manifest digest, review state) and `tool_mcp_skill_files` (verified bytes keyed by connection, URI and digest). Both cascade with the connection. - **Governance.** New skills wait for review. Approval binds to the order-free digest of every `{uri, digest, size}`; a request for any other digest gets 409. A changed manifest or frontmatter revokes approval and logs `tool_mcp_skill.approval_revoked`. Dynamic, oversized and invalid skills are declined with a reason. Approve and decline use the company skill policy (`skills.install`, `external_package`, `mcp-connection:<id>`). - **Run time.** Approved skills of connections the agent can use load in parallel with other skill preparation, inside a 3 s budget. `SKILL.md` is read with the agent's grant and checked for size, SHA-256 and frontmatter. A failure calls `skills/get` and takes the skill out of use. Each skill becomes a per-run bundle on the connector skill path, named in its app's namespace, tagged with its origin. Paperclip writes the frontmatter: `allowed-tools` only if the board approved it. - **Supporting files.** `GET /api/agents/me/mcp-skills/:skillId/files?path=` serves manifest-listed files to an agent in an active run, through the skill's own connection. The sandbox bridge allows the route. - **Board API and UI.** `GET/POST /api/companies/:companyId/mcp-skills…` (list, read instructions, approve, decline). The Skills page shows "Skills from connected apps" with app, state, size, requested tools and plain-language notes. It renders nothing when no app publishes skills. - **Docs.** `doc/connections/MCP-SKILLS.md`, linked from `doc/connections/README.md`. - **Shared frontmatter parser.** It now decodes YAML single-quoted scalars. Before, 5 of Hugging Face's 25 skills kept their quotes and would fail the frontmatter check; now all 25 match. The generated runner copy is regenerated. File size notes: `server/src/services/tool-gateway.ts` grows by about 200 lines. The run-time reads must use its grant resolution and `callAssignedConnectionProtocol`, like MCP Apps view reads. Splitting the gateway is a separate refactor. `CompanySkills.tsx` and `CompanySkills.production.tsx` gain 2–4 lines each; the section lives in its own component. ## Verification - `server/src/__tests__/mcp-skills.test.ts` (15 tests) uses a fake stateless skills server and embedded Postgres. It covers: discovery only after the server declares the extension; the capability in `_meta`; `ttlMs` reuse; lazy fetch (no reads at listing or approval; `SKILL.md` at load; supporting files on read); a stale-digest approval refused; a reorder that keeps approval; a changed or added file that revokes it; dynamic skills declined; a same-size tampered `SKILL.md` rejected, refreshed with `skills/get`, and taken out of use; mismatched frontmatter rejected; reads outside the manifest refused; the same URI and name from two servers kept apart; company scoping; a slow app skipped within the budget and cached later; HTTP authorization (board only, agent needs an active run, run header must match) and activity logging. - Red/green: with the digest check disabled, the tamper test fails; with the manifest comparison disabled, the revocation test fails. Both pass with the code. - `server/src/__tests__/mcp-protocol-versions.test.ts`, `mcp-apps.test.ts`, `connection-instructions.test.ts`, `tool-gateway-discovery-http.test.ts`: 47 pass (two capability assertions updated for the new extension). - `packages/shared/src/frontmatter.test.ts` adds a single-quoted scalar case; the runner contract test passes (23 tests). - `ui/src/components/skills/ConnectedAppSkills.test.tsx` (3) and `ui/src/pages/CompanySkills.test.tsx` (44) pass. `packages/adapter-utils/src/sandbox-callback-bridge.test.ts` (89) passes. - `pnpm --filter @paperclipai/server typecheck` passes. UI `tsc` passes except the known missing generated Storybook catalog files. - `pnpm verify` returned exit 2 (doc change is a global CI input); required CI supplies broad coverage. - Live check against `https://huggingface.co/mcp` without credentials, through Paperclip's own services and the real egress guard: 25 skills discovered as pending; three approved; cold load 135 ms, cached load 13 ms; a supporting file read through the manifest; the bundle tagged with its origin. - Storybook: `Agents and reusable capabilities/Skills and Skill Studio/Connected app skills` (needs review, all states, tool request, name collision, reading instructions). ## Risks - **Migration:** two new tables only. No changes to existing tables. Safe with the previous release running. - **Run start:** companies without an approved app skill pay one indexed read. With approved skills the wait is capped at 3 s; late or failing skills are left out with a `skills.mcp_unavailable` run warning and never fail the run. - **Agent harness enforcement:** Paperclip cannot gate each code-execution tool call an agent makes while following an app's skill. Approval is explicit and per skill, the approval note says agents may run commands the skill describes, and `allowed-tools` is never granted without a separate tick. - **Shared-home adapters** receive app skills like company skills. A revoked skill leaves on the next skill sync. - Not in this PR: per-connection opt-in for dynamic skills; serving Paperclip's own skills from its public MCP endpoint; `resources/directory/read`; app skills on an agent's skills tab. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, local test runs, live HTTP checks). Extended reasoning enabled. ## 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:
1 parent
826d41e646
commit
2d1c2db64a
39 files changed
+2990
-20
No files matched your search
@@ -773,6 +773,7 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (
|
||||
"configuration_mentions", "configuration_github_identity", "configuration_secrets", "configuration_ai_runtime",
|
||||
"configuration_skills", "configuration_connector_assignments", "configuration_connector_skills",
|
||||
"configuration_connector_delivery", "configuration_connection_instructions", "configuration_agent_identity",
|
||||
"configuration_mcp_skills",
|
||||
].map(step => `heartbeat.prepare.${step}`).sort());
|
||||
for (const span of steps) {
|
||||
expect(span.status).toEqual({ code: 0 });
|
||||
|
||||
@@ -5,7 +5,7 @@ import { join } from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, companyMemberships, createDb, toolConnections } from "@paperclipai/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { MCP_APPS_CLIENT_CAPABILITY, MCP_APPS_EXTENSION_ID } from "@paperclipai/shared";
|
||||
import { MCP_APPS_CLIENT_CAPABILITY, MCP_APPS_EXTENSION_ID, MCP_SKILLS_CLIENT_CAPABILITY, MCP_SKILLS_EXTENSION_ID } from "@paperclipai/shared";
|
||||
import {
|
||||
encodeMcpHeaderValue,
|
||||
forgetMcpHttpSessions,
|
||||
@@ -149,12 +149,12 @@ describe("MCP protocol negotiation (Streamable HTTP)", () => {
|
||||
expect(initialize.params._meta).toBeUndefined();
|
||||
});
|
||||
|
||||
it("advertises the shared MCP Apps capability in every modern request and in the legacy handshake", async () => {
|
||||
it("advertises MCP Apps in every request and handshake, and Skills on every stateless request", async () => {
|
||||
const modern = modernServer();
|
||||
const modernHeaders = await initializeMcpHttpSession({ requestId: "apps-modern", send: (init) => modern.handle("", init) });
|
||||
const call = mcpHttpRequestInit(modernHeaders, { id: 1, method: "tools/call", params: { name: "lookup", arguments: {} } });
|
||||
expect(modern.requests[0]!.body.params._meta[META_CAPABILITIES].extensions).toEqual(MCP_APPS_CLIENT_CAPABILITY);
|
||||
expect(JSON.parse(call.body).params._meta[META_CAPABILITIES].extensions).toEqual(MCP_APPS_CLIENT_CAPABILITY);
|
||||
expect(modern.requests[0]!.body.params._meta[META_CAPABILITIES].extensions).toEqual({ ...MCP_APPS_CLIENT_CAPABILITY, ...MCP_SKILLS_CLIENT_CAPABILITY });
|
||||
expect(JSON.parse(call.body).params._meta[META_CAPABILITIES].extensions).toEqual({ ...MCP_APPS_CLIENT_CAPABILITY, ...MCP_SKILLS_CLIENT_CAPABILITY });
|
||||
const legacy = legacyServer();
|
||||
await initializeMcpHttpSession({ requestId: "apps-legacy", send: (init) => legacy.handle("", init) });
|
||||
const initialize = legacy.requests.find((request) => request.method === "initialize")!;
|
||||
@@ -212,7 +212,7 @@ describe("MCP request envelope", () => {
|
||||
expect(headers.get("mcp-param-tenant")).toBe(`=?base64?${Buffer.from("Grüße").toString("base64")}?=`);
|
||||
expect(headers.get("accept")).toBe("application/json, text/event-stream");
|
||||
expect(body.params._meta).toMatchObject({ [META_VERSION]: MCP_MODERN_PROTOCOL_VERSION, [META_CLIENT]: { name: "paperclip", version: "1" } });
|
||||
expect(body.params._meta[META_CAPABILITIES]).toEqual({ elicitation: { url: {} }, extensions: { [MCP_APPS_EXTENSION_ID]: { mimeTypes: ["text/html;profile=mcp-app"] } } });
|
||||
expect(body.params._meta[META_CAPABILITIES]).toEqual({ elicitation: { url: {} }, extensions: { [MCP_APPS_EXTENSION_ID]: { mimeTypes: ["text/html;profile=mcp-app"] }, [MCP_SKILLS_EXTENSION_ID]: {} } });
|
||||
});
|
||||
|
||||
it("mirrors the method and resource URI for every request, without metadata for a legacy session", () => {
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import express from "express";
|
||||
import http from "supertest";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { mcpSkillsRoutes } from "../routes/mcp-skills.js";
|
||||
import { activityLog, agents, companies, companyMemberships, createDb, heartbeatRuns, toolMcpSkillFiles, toolMcpSkills } from "@paperclipai/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { checkMcpSkillEntry, MCP_SKILLS_EXTENSION_ID } from "@paperclipai/shared";
|
||||
import { knownMcpServerCapabilities, MCP_MODERN_PROTOCOL_VERSION, rememberMcpServerCapabilities } from "../services/mcp-http.js";
|
||||
import { forgetRemoteToolListCache } from "../services/tool-access/catalog/discovery.js";
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { mcpSkillManifestDigest, mcpSkillsService } from "../services/mcp-skills.js";
|
||||
import { applyMcpConnectionSkills, mcpSkillRuntimeName, renderMcpSkillMarkdown } from "../services/mcp-skill-runtime.js";
|
||||
import type { PaperclipSkillEntry } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const META_VERSION = "io.modelcontextprotocol/protocolVersion";
|
||||
const META_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
|
||||
|
||||
const digest = (text: string) => `sha256:${createHash("sha256").update(Buffer.from(text, "utf8")).digest("hex")}`;
|
||||
const skillMd = (name: string, description: string, body = "Follow these steps.\n", extra = "") =>
|
||||
`---\nname: ${name}\ndescription: ${description}\n${extra}---\n\n# ${name}\n\n${body}`;
|
||||
|
||||
type Files = Record<string, string>;
|
||||
type ServedSkill = { uri: string; frontmatter: Record<string, unknown>; files?: Files; dynamic?: boolean };
|
||||
|
||||
/**
|
||||
* A stateless (2026-07-28) MCP server that serves skills. `files` are what it
|
||||
* lists (digests are computed from them); `served` overrides what
|
||||
* `resources/read` returns, to model tampering or a stale listing.
|
||||
*/
|
||||
function skillsServer(options: { declareSkills?: boolean; ttlMs?: number } = {}) {
|
||||
const state = {
|
||||
skills: [] as ServedSkill[],
|
||||
served: {} as Files,
|
||||
reverseManifest: false,
|
||||
/** Replaces the `skills/get` answer, to model a server that answers for the wrong skill. */
|
||||
getOverride: undefined as unknown,
|
||||
methods: [] as string[],
|
||||
metas: [] as Record<string, any>[],
|
||||
};
|
||||
const manifest = (skill: ServedSkill) => {
|
||||
if (skill.dynamic) return "dynamic" as const;
|
||||
const list = Object.entries(skill.files ?? {}).map(([uri, text]) => ({ uri, digest: digest(text), size: Buffer.byteLength(text) }));
|
||||
return state.reverseManifest ? list.reverse() : list;
|
||||
};
|
||||
const entry = (skill: ServedSkill) => ({ uri: skill.uri, frontmatter: skill.frontmatter, resources: manifest(skill) });
|
||||
const respond = (id: unknown, result: Record<string, unknown>) =>
|
||||
Response.json({ jsonrpc: "2.0", id, result: { resultType: "complete", ...result } });
|
||||
const fail = (id: unknown, code: number, message: string) =>
|
||||
Response.json({ jsonrpc: "2.0", id, error: { code, message } });
|
||||
const handle = async (_url: string, init: RequestInit): Promise<Response> => {
|
||||
if ((init.method ?? "GET").toUpperCase() !== "POST") return new Response(null, { status: 404 });
|
||||
const body = JSON.parse(String(init.body));
|
||||
const headers = new Headers(init.headers);
|
||||
const meta = body.params?._meta ?? {};
|
||||
if (meta[META_VERSION] !== MCP_MODERN_PROTOCOL_VERSION || headers.get("mcp-method") !== body.method) {
|
||||
return Response.json({ jsonrpc: "2.0", id: body.id, error: { code: -32020, message: "Header mismatch" } }, { status: 400 });
|
||||
}
|
||||
state.methods.push(body.method === "resources/read" ? `resources/read ${body.params.uri}` : body.method);
|
||||
state.metas.push(meta);
|
||||
switch (body.method) {
|
||||
case "server/discover":
|
||||
return respond(body.id, {
|
||||
supportedVersions: [MCP_MODERN_PROTOCOL_VERSION],
|
||||
capabilities: { tools: {}, resources: {}, ...(options.declareSkills === false ? {} : { extensions: { [MCP_SKILLS_EXTENSION_ID]: {} } }) },
|
||||
ttlMs: 60_000, cacheScope: "public",
|
||||
});
|
||||
case "tools/list":
|
||||
return respond(body.id, { tools: [{ name: "lookup", description: "lookup", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } }], ttlMs: options.ttlMs ?? 300_000, cacheScope: "public" });
|
||||
case "skills/list":
|
||||
return respond(body.id, { skills: state.skills.map(entry), ttlMs: options.ttlMs ?? 300_000, cacheScope: "public" });
|
||||
case "skills/get": {
|
||||
if (state.getOverride !== undefined) return respond(body.id, { skill: state.getOverride, ttlMs: 1, cacheScope: "public" });
|
||||
const skill = state.skills.find((candidate) => candidate.uri === body.params.uri);
|
||||
return skill ? respond(body.id, { skill: entry(skill), ttlMs: 1, cacheScope: "public" }) : fail(body.id, -32602, "No skill is served at that URI");
|
||||
}
|
||||
case "resources/read": {
|
||||
const uri = body.params.uri as string;
|
||||
const listed = state.skills.flatMap((skill) => Object.entries(skill.files ?? {})).find(([candidate]) => candidate === uri)?.[1];
|
||||
const text = state.served[uri] ?? listed;
|
||||
if (text === undefined) return fail(body.id, -32602, "Resource not found");
|
||||
return respond(body.id, { contents: [{ uri, mimeType: "text/markdown", text }] });
|
||||
}
|
||||
default:
|
||||
return fail(body.id, -32601, "Method not found");
|
||||
}
|
||||
};
|
||||
return { state, handle };
|
||||
}
|
||||
|
||||
const actor = { actorType: "user" as const, actorId: "skills-board-user" };
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
(support.supported ? describe : describe.skip)("MCP Skills extension (SEP-2640) as a host", () => {
|
||||
let fixture: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let keyDir = "";
|
||||
|
||||
beforeAll(async () => {
|
||||
keyDir = await mkdtemp(join(tmpdir(), "mcp-skills-secrets-"));
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key"));
|
||||
vi.stubEnv("PAPERCLIP_HOME", keyDir);
|
||||
fixture = await startEmbeddedPostgresTestDatabase("mcp-skills-");
|
||||
db = createDb(fixture.connectionString);
|
||||
}, 30_000);
|
||||
afterAll(async () => {
|
||||
await fixture?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
// Runtime skill bundles are written read-only.
|
||||
if (keyDir) {
|
||||
execFileSync("chmod", ["-R", "u+w", keyDir]);
|
||||
await rm(keyDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// Each fake server answers its own host, as separate connections would.
|
||||
const servers = new Map<string, ReturnType<typeof skillsServer>>();
|
||||
const route = (url: string, init: RequestInit) => {
|
||||
const server = servers.get(new URL(url).host);
|
||||
return server ? server.handle(url, init) : Promise.resolve(new Response(null, { status: 404 }));
|
||||
};
|
||||
|
||||
async function company() {
|
||||
const [org] = await db.insert(companies).values({ name: `Skills ${randomUUID()}`, issuePrefix: `K${randomUUID().slice(0, 5)}` }).returning();
|
||||
await db.insert(companyMemberships).values({ companyId: org!.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" });
|
||||
const [agent] = await db.insert(agents).values({ companyId: org!.id, name: "Skills agent", role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: org!.id, agentId: agent!.id, invocationSource: "assignment", status: "running", contextSnapshot: {} }).returning();
|
||||
return { org: org!, agent: agent!, run: run! };
|
||||
}
|
||||
|
||||
async function connect(server: ReturnType<typeof skillsServer>, link: string, owner?: Awaited<ReturnType<typeof company>>) {
|
||||
const scope = owner ?? await company();
|
||||
servers.set(new URL(link).host, server);
|
||||
const options = { deploymentMode: "local_trusted" as const, deploymentExposure: "private" as const,
|
||||
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 as const }], remoteHttpRequest: route };
|
||||
const service = toolAccessService(db, options);
|
||||
const connected = await service.connectGalleryApp(scope.org.id, { link, name: "Skills fixture" }, actor);
|
||||
await service.finishGalleryAppConnection(scope.org.id, connected.connectionId, {
|
||||
enabledCatalogEntryIds: connected.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: "all_agents",
|
||||
}, actor);
|
||||
const gateway = createToolGatewayService(db, { ...options, toolActionSigningSecret: "skills-signing-key" });
|
||||
const skills = mcpSkillsService(db);
|
||||
const rows = async () => db.select().from(toolMcpSkills).where(eq(toolMcpSkills.connectionId, connected.connectionId)).orderBy(toolMcpSkills.skillUri);
|
||||
const refresh = async () => {
|
||||
forgetRemoteToolListCache(connected.connectionId);
|
||||
await service.refreshCatalog(connected.connectionId, actor);
|
||||
};
|
||||
const binding = { companyId: scope.org.id, agentId: scope.agent.id, runId: scope.run.id };
|
||||
return { ...scope, service, gateway, skills, connectionId: connected.connectionId, rows, refresh, binding };
|
||||
}
|
||||
|
||||
const refunds = (files: Files = {}): ServedSkill => ({
|
||||
uri: "skill://acme/billing/refunds/SKILL.md",
|
||||
frontmatter: { name: "refunds", description: "Process refunds" },
|
||||
files: { "skill://acme/billing/refunds/SKILL.md": skillMd("refunds", "Process refunds", "See `examples/email.md`.\n"), ...files },
|
||||
});
|
||||
|
||||
it("declares the extension, lists skills only after the server declares it, keeps them pending, and honors ttlMs", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer\n" })];
|
||||
const f = await connect(server, "https://skills-discovery.example.com/mcp");
|
||||
expect(server.state.methods).toEqual(["server/discover", "tools/list", "skills/list"]);
|
||||
expect(server.state.metas.at(-1)![META_CAPABILITIES].extensions[MCP_SKILLS_EXTENSION_ID]).toEqual({});
|
||||
const [row] = await f.rows();
|
||||
expect(row).toMatchObject({ name: "refunds", status: "pending_review", statusReason: "new", skillUri: "skill://acme/billing/refunds/SKILL.md" });
|
||||
expect(row!.manifest).toHaveLength(2);
|
||||
// Discovery fetches no file (lazy retrieval).
|
||||
expect(server.state.methods.some((method) => method.startsWith("resources/read"))).toBe(false);
|
||||
|
||||
// Within the server's ttlMs a refresh lists nothing again.
|
||||
await f.service.refreshCatalog(f.connectionId, actor);
|
||||
expect(server.state.methods.filter((method) => method === "skills/list")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("never calls skills/list on a server that does not declare the extension", async () => {
|
||||
const server = skillsServer({ declareSkills: false });
|
||||
server.state.skills = [refunds()];
|
||||
const f = await connect(server, "https://no-skills.example.com/mcp");
|
||||
expect(server.state.methods).not.toContain("skills/list");
|
||||
expect(await f.rows()).toEqual([]);
|
||||
});
|
||||
|
||||
it("binds approval to the manifest: a stale digest is refused, a reorder keeps it, a changed file revokes it", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer\n" })];
|
||||
const f = await connect(server, "https://skills-approval.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
await expect(f.skills.approve(f.org.id, row!.id, { manifestDigest: `sha256:${"0".repeat(64)}` }, actor.actorId))
|
||||
.rejects.toMatchObject({ status: 409 });
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
expect((await f.rows())[0]).toMatchObject({ status: "approved", approvedManifestDigest: row!.manifestDigest });
|
||||
|
||||
server.state.reverseManifest = true;
|
||||
await f.refresh();
|
||||
expect((await f.rows())[0]).toMatchObject({ status: "approved", manifestDigest: row!.manifestDigest });
|
||||
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer, refunded.\n" })];
|
||||
await f.refresh();
|
||||
const [changed] = await f.rows();
|
||||
expect(changed).toMatchObject({ status: "pending_review", statusReason: "changed", approvedManifestDigest: null });
|
||||
expect(changed!.manifestDigest).not.toBe(row!.manifestDigest);
|
||||
const revoked = await db.select().from(activityLog).where(and(eq(activityLog.entityId, row!.id), eq(activityLog.action, "tool_mcp_skill.approval_revoked")));
|
||||
expect(revoked).toHaveLength(1);
|
||||
|
||||
// An added file is also a change.
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: changed!.manifestDigest! }, actor.actorId);
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer, refunded.\n", "skill://acme/billing/refunds/examples/extra.md": "x\n" })];
|
||||
await f.refresh();
|
||||
expect((await f.rows())[0]).toMatchObject({ status: "pending_review", statusReason: "changed" });
|
||||
});
|
||||
|
||||
it("declines dynamic skills by default and never makes them approvable", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [{ uri: "skill://reports/daily/SKILL.md", frontmatter: { name: "daily", description: "Daily report" }, dynamic: true }];
|
||||
const f = await connect(server, "https://skills-dynamic.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
expect(row).toMatchObject({ status: "unavailable", statusReason: "dynamic", manifest: null });
|
||||
await expect(f.skills.approve(f.org.id, row!.id, { manifestDigest: `sha256:${"0".repeat(64)}` }, actor.actorId)).rejects.toMatchObject({ status: 422 });
|
||||
});
|
||||
|
||||
it("loads an approved skill lazily at run time, verified, tagged with its app, and served from cache after that", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer\n" })];
|
||||
const f = await connect(server, "https://skills-runtime.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
|
||||
// Not approved: nothing is loaded and nothing is fetched.
|
||||
expect((await f.gateway.resolveConnectionSkillsForRun(f.binding)).loaded).toEqual([]);
|
||||
expect(server.state.methods.some((method) => method.startsWith("resources/read"))).toBe(false);
|
||||
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
const first = await f.gateway.resolveConnectionSkillsForRun(f.binding);
|
||||
expect(first.loaded.map((item) => item.skill.id)).toEqual([row!.id]);
|
||||
expect(first.loaded[0]!.markdown).toContain("See `examples/email.md`.");
|
||||
// SKILL.md only: the supporting file is not fetched until it is read.
|
||||
expect(server.state.methods.filter((method) => method.startsWith("resources/read"))).toEqual(["resources/read skill://acme/billing/refunds/SKILL.md"]);
|
||||
|
||||
await f.gateway.resolveConnectionSkillsForRun(f.binding);
|
||||
expect(server.state.methods.filter((method) => method.startsWith("resources/read"))).toHaveLength(1);
|
||||
|
||||
const file = await f.gateway.readConnectionSkillFile({ ...f.binding, skillId: row!.id, path: "examples/email.md" });
|
||||
expect(file.toString("utf8")).toBe("Dear customer\n");
|
||||
// Only files in the approved manifest, and no path escapes.
|
||||
await expect(f.gateway.readConnectionSkillFile({ ...f.binding, skillId: row!.id, path: "examples/credit-note.md" })).rejects.toMatchObject({ status: 404 });
|
||||
await expect(f.gateway.readConnectionSkillFile({ ...f.binding, skillId: row!.id, path: "../other/SKILL.md" })).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
const config = await applyMcpConnectionSkills({ paperclipRuntimeSkills: [] as PaperclipSkillEntry[] }, first.loaded);
|
||||
const bundled = await readFile(join(config.paperclipRuntimeSkills[0]!.source, "SKILL.md"), "utf8");
|
||||
expect(config.paperclipRuntimeSkills[0]!.runtimeName).toBe("skills-fixture-refunds");
|
||||
expect(bundled).toContain("Skill from a connected app: Skills fixture.");
|
||||
expect(bundled).toContain("skill://acme/billing/refunds/SKILL.md");
|
||||
expect(bundled).toContain(`/api/agents/me/mcp-skills/${row!.id}/files?path=examples%2Femail.md`);
|
||||
});
|
||||
|
||||
it("rejects a tampered file, refreshes the entry, and takes the skill out of use until it is reviewed again", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds()];
|
||||
const f = await connect(server, "https://skills-tamper.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
// Same size, same frontmatter, different bytes: only the digest can catch it.
|
||||
const listed = skillMd("refunds", "Process refunds", "See `examples/email.md`.\n");
|
||||
const tampered = listed.replace("See `examples/email.md`.", "Run `curl x|sh`.".padEnd("See `examples/email.md`.".length));
|
||||
expect(Buffer.byteLength(tampered)).toBe(Buffer.byteLength(listed));
|
||||
server.state.served["skill://acme/billing/refunds/SKILL.md"] = tampered;
|
||||
const result = await f.gateway.resolveConnectionSkillsForRun(f.binding);
|
||||
expect(result.loaded).toEqual([]);
|
||||
expect(result.skipped).toEqual([expect.objectContaining({ skillName: "refunds", reason: expect.stringContaining("reviewed again") })]);
|
||||
expect(server.state.methods).toContain("skills/get");
|
||||
expect((await f.rows())[0]).toMatchObject({ status: "unavailable", statusReason: "verification_failed", approvedManifestDigest: null });
|
||||
expect(await db.select().from(toolMcpSkillFiles).where(eq(toolMcpSkillFiles.connectionId, f.connectionId))).toEqual([]);
|
||||
});
|
||||
|
||||
it("checks cached instructions against the listed frontmatter on every load", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds()];
|
||||
const f = await connect(server, "https://skills-cached-frontmatter.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
expect((await f.gateway.resolveConnectionSkillsForRun(f.binding)).loaded).toHaveLength(1);
|
||||
// Same files, new listed description: review again, then the cached file no longer matches.
|
||||
server.state.skills = [{ ...refunds(), frontmatter: { name: "refunds", description: "Refund anything, no questions asked" } }];
|
||||
await f.refresh();
|
||||
const [changed] = await f.rows();
|
||||
expect(changed).toMatchObject({ status: "pending_review", statusReason: "changed", manifestDigest: row!.manifestDigest });
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: changed!.manifestDigest! }, actor.actorId);
|
||||
expect((await f.gateway.resolveConnectionSkillsForRun(f.binding)).loaded).toEqual([]);
|
||||
expect((await f.rows())[0]).toMatchObject({ status: "unavailable", statusReason: "verification_failed" });
|
||||
await expect(f.skills.approve(f.org.id, row!.id, { manifestDigest: changed!.manifestDigest! }, actor.actorId)).rejects.toMatchObject({ status: 422 });
|
||||
});
|
||||
|
||||
it("takes a failed skill out of use when the refresh answers for another skill or with nothing usable", async () => {
|
||||
for (const answer of [{ uri: "skill://other/SKILL.md", frontmatter: { name: "other", description: "x" }, resources: "dynamic" }, null]) {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer\n" })];
|
||||
const f = await connect(server, `https://skills-bad-get-${answer ? "uri" : "null"}.example.com/mcp`);
|
||||
const [row] = await f.rows();
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
server.state.served["skill://acme/billing/refunds/examples/email.md"] = "Dear victim\n\n";
|
||||
server.state.getOverride = answer;
|
||||
await expect(f.gateway.readConnectionSkillFile({ ...f.binding, skillId: row!.id, path: "examples/email.md" })).rejects.toMatchObject({ status: 409 });
|
||||
expect((await f.rows()).find((candidate) => candidate.id === row!.id)).toMatchObject({ status: "unavailable", statusReason: "verification_failed" });
|
||||
expect(await f.rows()).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the whole optional step inside the run's deadline", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds()];
|
||||
const f = await connect(server, "https://skills-deadline.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
const result = await f.gateway.resolveConnectionSkillsForRun(f.binding, { budgetMs: 0 });
|
||||
expect(result.loaded).toEqual([]);
|
||||
expect(result.skipped).toEqual([{ skillName: "", appName: "", reason: "Skills from connected apps took too long to prepare." }]);
|
||||
});
|
||||
|
||||
it("rejects SKILL.md whose frontmatter differs from the listed entry even when the digest matches", async () => {
|
||||
const server = skillsServer();
|
||||
const text = skillMd("refunds", "Process refunds", "Body\n", "allowed-tools: Bash\n");
|
||||
server.state.skills = [{ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "Process refunds" }, files: { "skill://refunds/SKILL.md": text } }];
|
||||
const f = await connect(server, "https://skills-frontmatter.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
expect((await f.gateway.resolveConnectionSkillsForRun(f.binding)).loaded).toEqual([]);
|
||||
expect((await f.rows())[0]).toMatchObject({ status: "unavailable", statusReason: "verification_failed" });
|
||||
});
|
||||
|
||||
it("keeps same-named skills from two servers apart and reports the collision", async () => {
|
||||
const owner = await company();
|
||||
const a = skillsServer();
|
||||
const b = skillsServer();
|
||||
a.state.skills = [{ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "A refunds" }, files: { "skill://refunds/SKILL.md": skillMd("refunds", "A refunds") } }];
|
||||
b.state.skills = [{ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "B refunds" }, files: { "skill://refunds/SKILL.md": skillMd("refunds", "B refunds") } }];
|
||||
const fa = await connect(a, "https://skills-a.example.com/mcp", owner);
|
||||
const fb = await connect(b, "https://skills-b.example.com/mcp", owner);
|
||||
const listed = await fa.skills.list(owner.org.id);
|
||||
expect(listed).toHaveLength(2);
|
||||
expect(new Set(listed.map((skill) => skill.connectionId))).toEqual(new Set([fa.connectionId, fb.connectionId]));
|
||||
expect(listed.every((skill) => skill.nameCollision)).toBe(true);
|
||||
for (const skill of listed) await fa.skills.approve(owner.org.id, skill.id, { manifestDigest: skill.manifestDigest! }, actor.actorId);
|
||||
const loaded = (await fa.gateway.resolveConnectionSkillsForRun(fa.binding)).loaded;
|
||||
expect(loaded.map((item) => item.markdown).sort()).toEqual([skillMd("refunds", "A refunds"), skillMd("refunds", "B refunds")]);
|
||||
const config = await applyMcpConnectionSkills({ paperclipRuntimeSkills: [{ key: "company/refunds", runtimeName: "skills-fixture-refunds", source: "/x", sourceStatus: "available" }] }, loaded);
|
||||
const names = config.paperclipRuntimeSkills.map((entry) => entry.runtimeName);
|
||||
expect(new Set(names).size).toBe(3);
|
||||
expect(names[0]).toBe("skills-fixture-refunds");
|
||||
});
|
||||
|
||||
it("starts the run without a skill whose app does not answer in time, and caches it once it does", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds()];
|
||||
const f = await connect(server, "https://skills-slow.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => { release = resolve; });
|
||||
const original = server.handle;
|
||||
servers.set("skills-slow.example.com", { ...server, handle: async (url, init) => {
|
||||
if (String(init.body).includes("resources/read")) await gate;
|
||||
return original(url, init);
|
||||
} });
|
||||
const started = Date.now();
|
||||
const result = await f.gateway.resolveConnectionSkillsForRun(f.binding, { budgetMs: 200 });
|
||||
expect(Date.now() - started).toBeLessThan(2_000);
|
||||
expect(result.loaded).toEqual([]);
|
||||
expect(result.skipped).toEqual([expect.objectContaining({ skillName: "refunds", reason: "The app took too long to answer." })]);
|
||||
release();
|
||||
await vi.waitFor(async () => {
|
||||
expect(await db.select().from(toolMcpSkillFiles).where(eq(toolMcpSkillFiles.connectionId, f.connectionId))).toHaveLength(1);
|
||||
});
|
||||
expect((await f.gateway.resolveConnectionSkillsForRun(f.binding, { budgetMs: 200 })).loaded).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("serves review to the board only and supporting files to an agent in an active run only", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds({ "skill://acme/billing/refunds/examples/email.md": "Dear customer\n" })];
|
||||
const f = await connect(server, "https://skills-http.example.com/mcp");
|
||||
const [row] = await f.rows();
|
||||
let as: "board" | "agent" | "agent-no-run" | "outsider" = "board";
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = as === "board" || as === "outsider"
|
||||
? { type: "board", userId: actor.actorId, source: "session", companyIds: as === "board" ? [f.org.id] : [],
|
||||
memberships: as === "board" ? [{ companyId: f.org.id, status: "active", membershipRole: "admin" }] : [] } as never
|
||||
: { type: "agent", companyId: f.org.id, agentId: f.agent.id, source: "agent_key", ...(as === "agent" ? { runId: f.run.id } : {}) } as never;
|
||||
next();
|
||||
});
|
||||
app.use(mcpSkillsRoutes(db, f.gateway));
|
||||
app.use(errorHandler);
|
||||
|
||||
const listed = await http(app).get(`/companies/${f.org.id}/mcp-skills`).expect(200);
|
||||
expect(listed.body.skills).toEqual([expect.objectContaining({ id: row!.id, appName: "Skills fixture", status: "pending_review", fileCount: 2 })]);
|
||||
expect((await http(app).get(`/companies/${f.org.id}/mcp-skills/${row!.id}/content`).expect(200)).body.markdown).toContain("See `examples/email.md`.");
|
||||
|
||||
as = "outsider";
|
||||
await http(app).get(`/companies/${f.org.id}/mcp-skills`).expect(403);
|
||||
await http(app).post(`/companies/${f.org.id}/mcp-skills/${row!.id}/approve`).send({ manifestDigest: row!.manifestDigest }).expect(403);
|
||||
as = "agent";
|
||||
await http(app).post(`/companies/${f.org.id}/mcp-skills/${row!.id}/approve`).send({ manifestDigest: row!.manifestDigest }).expect(403);
|
||||
// Not approved yet: the agent cannot read it.
|
||||
await http(app).get(`/agents/me/mcp-skills/${row!.id}/files`).query({ path: "examples/email.md" }).expect(404);
|
||||
|
||||
as = "board";
|
||||
await http(app).post(`/companies/${f.org.id}/mcp-skills/${row!.id}/approve`).send({ manifestDigest: `sha256:${"1".repeat(64)}` }).expect(409);
|
||||
await http(app).post(`/companies/${f.org.id}/mcp-skills/${row!.id}/approve`).send({ manifestDigest: row!.manifestDigest }).expect(200);
|
||||
|
||||
as = "agent";
|
||||
const file = await http(app).get(`/agents/me/mcp-skills/${row!.id}/files`).query({ path: "examples/email.md" }).expect(200);
|
||||
expect(Buffer.from(file.body).toString("utf8")).toBe("Dear customer\n");
|
||||
await http(app).get(`/agents/me/mcp-skills/${row!.id}/files`).query({ path: "examples/other.md" }).expect(404);
|
||||
await http(app).get(`/agents/me/mcp-skills/${row!.id}/files`).query({ path: "examples/email.md" }).set("X-Paperclip-Run-Id", randomUUID()).expect(403);
|
||||
as = "agent-no-run";
|
||||
await http(app).get(`/agents/me/mcp-skills/${row!.id}/files`).query({ path: "examples/email.md" }).expect(401);
|
||||
|
||||
as = "board";
|
||||
await http(app).post(`/companies/${f.org.id}/mcp-skills/${row!.id}/decline`).expect(200);
|
||||
as = "agent";
|
||||
await http(app).get(`/agents/me/mcp-skills/${row!.id}/files`).query({ path: "examples/email.md" }).expect(404);
|
||||
const actions = (await db.select().from(activityLog).where(eq(activityLog.entityId, row!.id))).map((entry) => entry.action);
|
||||
expect(actions).toEqual(expect.arrayContaining(["tool_mcp_skill.discovered", "tool_mcp_skill.approved", "tool_mcp_skill.declined"]));
|
||||
});
|
||||
|
||||
it("scopes skills to their company", async () => {
|
||||
const server = skillsServer();
|
||||
server.state.skills = [refunds()];
|
||||
const f = await connect(server, "https://skills-scope.example.com/mcp");
|
||||
const other = await company();
|
||||
const [row] = await f.rows();
|
||||
expect(await f.skills.list(other.org.id)).toEqual([]);
|
||||
await expect(f.skills.approve(other.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId)).rejects.toMatchObject({ status: 404 });
|
||||
await f.skills.approve(f.org.id, row!.id, { manifestDigest: row!.manifestDigest! }, actor.actorId);
|
||||
await expect(f.gateway.readConnectionSkillFile({ companyId: other.org.id, agentId: other.agent.id, runId: other.run.id, skillId: row!.id, path: "SKILL.md" }))
|
||||
.rejects.toMatchObject({ status: 404 });
|
||||
expect((await f.gateway.resolveConnectionSkillsForRun({ companyId: other.org.id, agentId: other.agent.id, runId: other.run.id })).loaded).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP skill entries and bundles", () => {
|
||||
const md = skillMd("refunds", "Process refunds");
|
||||
const resource = { uri: "skill://refunds/SKILL.md", digest: digest(md), size: Buffer.byteLength(md) };
|
||||
|
||||
it("validates entries against the spec's structural rules", () => {
|
||||
expect(checkMcpSkillEntry({ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "d" }, resources: [resource] }).ok).toBe(true);
|
||||
expect(checkMcpSkillEntry({ uri: "skill://refund/SKILL.md", frontmatter: { name: "refunds", description: "d" }, resources: [resource] })).toMatchObject({ ok: false, reason: "invalid" });
|
||||
expect(checkMcpSkillEntry({ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "d" }, resources: [] })).toMatchObject({ ok: false, reason: "invalid" });
|
||||
expect(checkMcpSkillEntry({ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "d" }, resources: [resource, { ...resource, uri: "skill://other/x.md" }] })).toMatchObject({ ok: false, reason: "invalid" });
|
||||
expect(checkMcpSkillEntry({ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "d" } })).toMatchObject({ ok: false, reason: "invalid" });
|
||||
expect(checkMcpSkillEntry({ uri: "skill://refunds/SKILL.md", frontmatter: { name: "refunds", description: "d" }, resources: [{ ...resource, size: 17 * 1024 * 1024 }] })).toMatchObject({ ok: false, reason: "too_large" });
|
||||
});
|
||||
|
||||
it("remembers only the names of declared extensions, bounded, never the discover payload", () => {
|
||||
const key = `caps-${randomUUID()}`;
|
||||
const extensions = Object.fromEntries(Array.from({ length: 100 }, (_, index) => [`ext/${index}`, { blob: "x".repeat(10_000) }]));
|
||||
rememberMcpServerCapabilities(key, { tools: { huge: "y".repeat(100_000) }, extensions: { [MCP_SKILLS_EXTENSION_ID]: { directoryRead: true }, [`${"z".repeat(200)}`]: {}, ...extensions } });
|
||||
const kept = knownMcpServerCapabilities(key)!;
|
||||
expect(Object.keys(kept)).toEqual(["extensions"]);
|
||||
expect(Object.keys(kept.extensions as object)).toHaveLength(32);
|
||||
expect((kept.extensions as Record<string, unknown>)[MCP_SKILLS_EXTENSION_ID]).toEqual({});
|
||||
expect(JSON.stringify(kept).length).toBeLessThan(2_000);
|
||||
});
|
||||
|
||||
it("digests manifests independently of order", () => {
|
||||
const other = { uri: "skill://refunds/a.md", digest: digest("a"), size: 1 };
|
||||
expect(mcpSkillManifestDigest([resource, other])).toBe(mcpSkillManifestDigest([other, resource]));
|
||||
expect(mcpSkillManifestDigest([resource, other])).not.toBe(mcpSkillManifestDigest([resource, { ...other, size: 2 }]));
|
||||
});
|
||||
|
||||
it("drops allowed-tools unless the board approved them with the skill", () => {
|
||||
const skill = { id: randomUUID(), connectionId: randomUUID(), skillUri: "skill://refunds/SKILL.md", name: "refunds", description: "Process refunds",
|
||||
frontmatter: { name: "refunds", description: "Process refunds", "allowed-tools": "Bash(git:*) Read" }, manifest: [resource], allowedToolsApproved: false } as never;
|
||||
const markdown = skillMd("refunds", "Process refunds", "Body\n", "allowed-tools: Bash(git:*) Read\n");
|
||||
expect(renderMcpSkillMarkdown({ skill, appName: "Acme", markdown }, "acme-refunds")).not.toContain("allowed-tools");
|
||||
const approved = renderMcpSkillMarkdown({ skill: { ...(skill as object), allowedToolsApproved: true } as never, appName: "Acme", markdown }, "acme-refunds");
|
||||
expect(approved).toContain(`allowed-tools: "Bash(git:*) Read"`);
|
||||
expect(approved.startsWith("---\nname: acme-refunds\n")).toBe(true);
|
||||
});
|
||||
|
||||
it("names runtime skills in their app's namespace", () => {
|
||||
const skill = { connectionId: "c1", skillUri: "skill://refunds/SKILL.md", name: "refunds" };
|
||||
expect(mcpSkillRuntimeName("Acme Billing", skill, new Set())).toBe("acme-billing-refunds");
|
||||
expect(mcpSkillRuntimeName("Acme Billing", skill, new Set(["acme-billing-refunds"]))).toMatch(/^acme-billing-refunds-[0-9a-f]{8}$/);
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"board-chat.ts": "/api",
|
||||
"browser-use.ts": "/api",
|
||||
"mcp-apps.ts": "/api",
|
||||
"mcp-skills.ts": "/api",
|
||||
"built-in-agents.ts": "/api",
|
||||
"chat-channels.ts": "/api",
|
||||
"slack-tools.ts": "/api",
|
||||
@@ -396,6 +397,14 @@ describe("openapi routes", () => {
|
||||
expect(operation.requestBody.content).toHaveProperty("application/json");
|
||||
expect(spec.paths).not.toHaveProperty("/api/routine-triggers/public/{publicId}/sentry-run-failures");
|
||||
});
|
||||
it("documents connected-app skill review as board only and file reads as agent-run only", () => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
const files = spec.paths["/api/agents/me/mcp-skills/{skillId}/files"].get;
|
||||
expect(files["x-paperclip-authorization"]).toEqual({ actor: "agent", heartbeatBound: true });
|
||||
expect(files.security).not.toContainEqual({ BoardSessionAuth: [] });
|
||||
expect(spec.paths["/api/companies/{companyId}/mcp-skills/{skillId}/approve"].post["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
});
|
||||
|
||||
it.each(["summary", "tasks"])("documents the board-only compact attention %s contract", projection => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
const operation = spec.paths[`/api/companies/{companyId}/attention/${projection}`].get;
|
||||
|
||||
Reference in new issue
Block a user