Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 90 additions & 4 deletions app/mcp/__tests__/oauthRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ it.each([false, true])(
"list_artists",
"open_recoup_workflows",
"open_recoup_workflows_sidebar",
"recoup_skills",
]);
const result = await client.callTool({ name: "get_tasks", arguments: {} });
expect(result.isError).not.toBe(true);
Expand Down Expand Up @@ -185,6 +186,14 @@ it("advertises native skills and serves their manifests and files through authen
expect(listing.result.cacheScope).toBe("private");
expect(listing.result.skills.map((skill: { uri: string }) => skill.uri)).toEqual([publicSkill]);

vi.stubEnv("OAUTH_ISSUER", "");
vi.stubEnv("OAUTH_INDEX_KEY", "");
const legacyCredential = await (
await POST(modernRequest("tools/call", { name: "recoup_skills", arguments: {} }))
).json();
expect(legacyCredential.result.isError).toBeFalsy();
expect(legacyCredential.result.content[0].text).toContain("recoup-public-test");

const lookup = await (await POST(modernRequest("skills/get", { uri: publicSkill }))).json();
expect(lookup.result.skill).toEqual(listing.result.skills[0]);
const uri = "skill://recoup-public-test/references/checklist.md";
Expand All @@ -206,8 +215,8 @@ it("advertises native skills and serves their manifests and files through authen

isRecoupAdmin.mockResolvedValue(true);
const staffOnMain = await (await POST(modernRequest("skills/get", { uri: staffSkill }))).json();
expect(staffOnMain.error.code).toBe(-32602);
expect(isRecoupAdmin).not.toHaveBeenCalled();
expect(staffOnMain.result.skill.uri).toBe(staffSkill);
expect(isRecoupAdmin).toHaveBeenCalledWith("member");
});

it("uses the same full OAuth tool restrictions and account binding on modern MCP", async () => {
Expand All @@ -224,6 +233,7 @@ it("uses the same full OAuth tool restrictions and account binding on modern MCP
"list_artists",
"open_recoup_workflows",
"open_recoup_workflows_sidebar",
"recoup_skills",
]);
const called = await (
await POST(modernRequest("tools/call", { name: "get_tasks", arguments: {} }))
Expand All @@ -243,10 +253,9 @@ it("serves public skills to limited OAuth grants without elevating their tool pe
scopes: access.scopes,
extra: { accountId: access.accountId, oauth: access },
});
isRecoupAdmin.mockResolvedValue(true);
isRecoupAdmin.mockResolvedValue(false);
const listing = await (await POST(modernRequest("skills/list"))).json();
expect(listing.result.skills.map((skill: { uri: string }) => skill.uri)).toEqual([publicSkill]);
expect(isRecoupAdmin).not.toHaveBeenCalled();
const write = await POST(
modernRequest("tools/call", { name: "create_new_artist", arguments: { name: "Fixture" } }),
);
Expand Down Expand Up @@ -352,3 +361,80 @@ it("grants staff skills to the exact configured account without requiring organi
verify.mockResolvedValue({ ...auth, extra: { accountId: grantedAccount } });
expect((await staffPOST(request())).status).toBe(403);
});

const checkFullOAuthRateLimit = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock("@/lib/mcp/oauth/checkFullOAuthRateLimit", () => ({ checkFullOAuthRateLimit }));

const getVerifiedPrivyEmails = vi.hoisted(() => vi.fn());
vi.mock("@/lib/privy/getVerifiedPrivyEmails", () => ({ getVerifiedPrivyEmails }));

it("uses the signed-in identity for native skills and the ChatGPT tool on the same connection", async () => {
const subject = "did:privy:connector-staff";
access.scopes = ["mcp:read"];
verify.mockResolvedValue({
token: "test",
clientId: access.clientId,
scopes: access.scopes,
extra: { accountId: access.accountId, oauth: { ...access, subject } },
});
isRecoupAdmin.mockResolvedValue(false);
const client = new Client({ name: "connector-fixture", version: "1" });
await client.connect(
new StreamableHTTPClientTransport(new URL(access.resource), {
requestInit: { headers: { Authorization: "Bearer test" } },
fetch: async (input, init) => POST(new Request(input, init)),
}),
);
const tool = (args: Record<string, unknown>) =>
client.callTool({ name: "recoup_skills", arguments: args });
try {
getVerifiedPrivyEmails.mockResolvedValue(["someone@recoupable.com.example"]);
const publicList = await tool({});
expect(JSON.stringify(publicList)).toContain("recoup-public-test");
expect(JSON.stringify(publicList)).not.toContain("recoup-internal-test");
expect((await tool({ skill: "recoup-internal-test" })).isError).toBe(true);
expect((await tool({ file: "SKILL.md" })).isError).toBe(true);
expect((await tool({ skill: "recoup-public-test", query: "something" })).isError).toBe(true);
expect(checkFullOAuthRateLimit).toHaveBeenCalledWith("recoup_skills", access.accountId);

checkFullOAuthRateLimit.mockRejectedValueOnce(
new Error("Tool rate limit reached; retry in 6 seconds"),
);
const throttled = await tool({});
expect(throttled.isError).toBe(true);
expect(JSON.stringify(throttled)).toContain("retry in 6 seconds");

getVerifiedPrivyEmails.mockResolvedValue(["staff@recoupable.com"]);
const staffList = await tool({});
expect(JSON.stringify(staffList)).toContain("recoup-public-test");
expect(JSON.stringify(staffList)).toContain("recoup-internal-test");
expect(JSON.stringify(await tool({ skill: "recoup-internal-test" }))).toContain(
"name: recoup-internal-test",
);
expect(
JSON.stringify(await tool({ skill: "recoup-public-test", file: "references/checklist.md" })),
).toContain("Checklist");
expect(
(await tool({ skill: "recoup-public-test", file: "../recoup-internal-test/SKILL.md" }))
.isError,
).toBe(true);
expect(getVerifiedPrivyEmails).toHaveBeenCalledWith(subject);

const native = await (await POST(modernRequest("skills/list"))).json();
expect(native.result.skills.map((skill: { uri: string }) => skill.uri).sort()).toEqual(
[staffSkill, publicSkill].sort(),
);

checkFullOAuthRateLimit.mockRejectedValueOnce(
new Error("Tool rate limit reached; retry in 6 seconds"),
);
expect((await POST(modernRequest("skills/list"))).status).toBe(500);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This assertion locks native skill requests to HTTP 500 when the shared rate limit rejects, so native clients receive a generic server failure instead of an MCP error or retry signal. Handle the rate-limit exception in the native handler and return the appropriate MCP error response rather than treating this 500 as the expected contract.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/mcp/__tests__/oauthRoute.test.ts, line 431:

<comment>This assertion locks native skill requests to HTTP 500 when the shared rate limit rejects, so native clients receive a generic server failure instead of an MCP error or retry signal. Handle the rate-limit exception in the native handler and return the appropriate MCP error response rather than treating this 500 as the expected contract.</comment>

<file context>
@@ -417,6 +425,11 @@ it("uses the signed-in identity for native skills and the ChatGPT tool on the sa
+    checkFullOAuthRateLimit.mockRejectedValueOnce(
+      new Error("Tool rate limit reached; retry in 6 seconds"),
+    );
+    expect((await POST(modernRequest("skills/list"))).status).toBe(500);
+
     getVerifiedPrivyEmails.mockResolvedValue([]);
</file context>


getVerifiedPrivyEmails.mockResolvedValue([]);
expect((await tool({ skill: "recoup-internal-test" })).isError).toBe(true);
const revoked = await (await POST(modernRequest("resources/read", { uri: staffSkill }))).json();
expect(revoked.error).toBeDefined();
} finally {
await client.close();
}
});
9 changes: 7 additions & 2 deletions app/mcp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { setOAuthMcpHeaders } from "@/lib/mcp/oauth/setOAuthMcpHeaders";
import { registerAllTools } from "@/lib/mcp/tools";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { createModernRecoupHandler } from "@/lib/mcp/skills/createModernRecoupHandler";
import { registerRecoupSkillsTool } from "@/lib/mcp/skills/registerRecoupSkillsTool";
import { createMcpHandler, withMcpAuth } from "mcp-handler";
import { verifyBearerToken } from "@/lib/mcp/verifyApiKey";
import { registerOAuthTools } from "@/lib/mcp/oauth/registerOAuthTools";
Expand All @@ -23,9 +24,13 @@ function createRecoupHandlers(
version: string,
withSkills = true,
) {
const registerConnection = (server: McpServer) => {
register(server);
if (withSkills) registerRecoupSkillsTool(server);
};
return {
legacy: createMcpHandler(register, { serverInfo: createRecoupServerInfo(version) }),
modern: createModernRecoupHandler(register, version, withSkills),
legacy: createMcpHandler(registerConnection, { serverInfo: createRecoupServerInfo(version) }),
modern: createModernRecoupHandler(registerConnection, version, withSkills),
};
}

Expand Down
57 changes: 26 additions & 31 deletions docs/mcp-skills.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,35 @@
# Recoup Skills over MCP

Recoup serves the native Skills extension (`io.modelcontextprotocol/skills`)
to clients using MCP `2026-07-28`.

## Claude Code setup

Connect Recoup for customer-facing skills and tools. Recoup staff can add the
second connection for internal skills. Authorize Recoup Staff with the full
tools permission and a Recoup organization member account or a staff skills grant.

```sh
claude mcp add --transport http recoup https://api.recoupable.dev/mcp
claude mcp add --transport http recoup-staff https://api.recoupable.dev/mcp/staff
```

Use `/skills` to find skills from both connections. For example, use
`/recoup:recoup-song-check-credits` or `/recoup-staff:recoup-internal-weekly-usage-review`.
Existing Recoup connections already use the first endpoint. Recoup Staff serves
skills and their resources. Recoup serves the tools those skills may need.
Selected Context grants retain their Context-only surface.

Both catalogs fit within Claude Code's 100-skill limit per connection.
[Claude Code MCP skill limits](https://code.claude.com/docs/en/mcp#mcp-skill-limitations)
Use the Recoup connector at `https://api.recoupable.dev/mcp` and sign in to
Recoup. Signed-in accounts using the standard connector grant can use
customer-facing skills. The connector
also makes internal skills available to Recoup organization members, accounts
with a staff skills grant, and OAuth users whose Recoup sign-in identity has a
currently verified `@recoupable.com` email. These grants apply to skill
content. Recoup tool actions continue to enforce their existing permissions.

In ChatGPT, ask the connected Recoup app to find or use a Recoup skill. The
`recoup_skills` tool searches the authorized catalog and reads skill
instructions and supporting files. ChatGPT's plugin listing shows the skills
included in the submitted plugin package.

Clients with native Skills over MCP support can also use `skills/list`,
`skills/get`, and `resources/read` on the same connection. For Claude Code,
use `/skills` or ask Recoup to find a skill by name if its menu reaches the
client's display limit. Selected Context grants keep their workspace-only
tool surface.

## Granting staff skills access

Use the server-side `RECOUP_STAFF_SKILL_ACCOUNT_IDS` setting for accounts that
need access to staff skills without organization membership. Set it to a
comma-separated list of exact Recoup account IDs. This grants access only to
the staff skills connection. The account still needs full tools consent.
Use the server-side `RECOUP_STAFF_SKILL_ACCOUNT_IDS` setting for explicit
grants. Set it to a comma-separated list of exact Recoup account IDs.

Use an account with customer-facing access when scanning or packaging the
public plugin so the submitted package contains only customer-facing skills.

## Updating the catalog

The [Skills repository](https://github.com/recoupable/skills) owns the skill
source and supports the existing install paths. To release a catalog update,
bump the full Skills commit SHA in `scripts/mcp-skills/build.mjs` and run
`pnpm build:mcp-skills`. The build validates both catalogs and checks their
sizes against Claude Code's limit. Each deployment packages the same skill
definitions and supporting files until the next API release.
source. To release a catalog update, bump the Skills commit SHA in
`scripts/mcp-skills/build.mjs` and run `pnpm build:mcp-skills`. This validates
the catalog and packages the skill definitions and supporting files with the API.
15 changes: 13 additions & 2 deletions lib/mcp/skills/createModernRecoupHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { z } from "zod";
import { createRecoupServerInfo } from "../createRecoupServerInfo";
import type { McpAuthInfo } from "../verifyApiKey";
import { getRecoupSkills } from "./getRecoupSkills";
import { resolveRecoupSkillsAudience } from "./resolveRecoupSkillsAudience";

type LegacyTool = (
args: unknown,
Expand All @@ -18,7 +19,7 @@ export function createModernRecoupHandler(
withSkills = true,
) {
return createMcpHandler(
async ({ authInfo }) => {
async ({ authInfo, requestInfo }) => {
const auth = authInfo as McpAuthInfo | undefined;
const server = new McpServer(createRecoupServerInfo(version));

Expand Down Expand Up @@ -55,7 +56,17 @@ export function createModernRecoupHandler(
};
register(registration as unknown as LegacyServer);

if (withSkills) (await getRecoupSkills("public")).attach(server);
if (withSkills) {
const method = requestInfo?.headers.get("Mcp-Method");
const skillRequest =
method === "skills/list" ||
method === "skills/get" ||
method === "resources/directory/read" ||
(method === "resources/read" &&
requestInfo?.headers.get("Mcp-Name") !== "ui://recoup/explore.html");
const audience = skillRequest ? await resolveRecoupSkillsAudience(auth) : undefined;
(await getRecoupSkills(audience ?? "public")).attach(server);
}
return server;
},
{ legacy: "reject" },
Expand Down
12 changes: 5 additions & 7 deletions lib/mcp/skills/getRecoupSkills.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { join } from "node:path";
import { SkillsExtension, type SkillCatalog } from "@modelcontextprotocol/server/ext/skills";
import { nodeSkillFiles } from "@modelcontextprotocol/server/ext/skills/node";
import { isStaffSkill } from "./isStaffSkill.mjs";
import { recoupSkillFiles } from "./recoupSkillFiles";

type Audience = "public" | "staff";
type Audience = "public" | "staff" | "all";

const files = nodeSkillFiles(join(process.cwd(), ".mcp-skills/generated"));
const catalogs = new Map<Audience, Promise<SkillCatalog>>();

/** Build the catalog from the immutable deployment bundle once per audience. */
Expand All @@ -15,10 +13,10 @@ export function getRecoupSkills(audience: Audience): Promise<SkillCatalog> {

const catalog = SkillsExtension.load(
{
read: path => files.read(path),
read: path => recoupSkillFiles.read(path),
list: async path => {
const children = await files.list(path);
return path
const children = await recoupSkillFiles.list(path);
return path || audience === "all"
? children
: children.filter(child => isStaffSkill(child.name) === (audience === "staff"));
},
Expand Down
23 changes: 23 additions & 0 deletions lib/mcp/skills/hasRecoupStaffSkills.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { McpAuthInfo } from "../verifyApiKey";

/** Staff skills are a read entitlement independent of administrative and write permissions. */
export async function hasRecoupStaffSkills(
accountId: string,
auth?: McpAuthInfo,
): Promise<boolean> {
if (!accountId || auth?.extra.oauth?.selectedContext) return false;
if (process.env.RECOUP_STAFF_SKILL_ACCOUNT_IDS?.split(",").some(id => id.trim() === accountId))
return true;

try {
const { isRecoupAdmin } = await import("@/lib/organizations/isRecoupAdmin");
if (await isRecoupAdmin(accountId)) return true;
const subject = auth?.extra.oauth?.subject;
if (!subject) return false;
const { getVerifiedPrivyEmails } = await import("@/lib/privy/getVerifiedPrivyEmails");
const emails = await getVerifiedPrivyEmails(subject);
return emails.some(email => email.split("@").at(-1) === "recoupable.com");
} catch {
return false;
}
}
7 changes: 7 additions & 0 deletions lib/mcp/skills/readRecoupSkillFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { recoupSkillFiles } from "./recoupSkillFiles";

/** Read a file selected from an authorized catalog manifest. */
export async function readRecoupSkillFile(uri: string) {
const url = new URL(uri);
return recoupSkillFiles.read(`${url.hostname}${decodeURIComponent(url.pathname)}`);
}
4 changes: 4 additions & 0 deletions lib/mcp/skills/recoupSkillFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { join } from "node:path";
import { nodeSkillFiles } from "@modelcontextprotocol/server/ext/skills/node";

export const recoupSkillFiles = nodeSkillFiles(join(process.cwd(), ".mcp-skills/generated"));
29 changes: 29 additions & 0 deletions lib/mcp/skills/recoupSkillsToolSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { z } from "zod";

export const recoupSkillsToolSchema = z
.object({
query: z
.string()
.trim()
.max(200)
.optional()
.describe("Topic or words to find in skill names and descriptions"),
offset: z.number().int().min(0).optional().describe("Next offset from a previous search"),
skill: z
.string()
.regex(/^[a-z0-9-]{1,64}$/)
.optional()
.describe("Exact skill name to load"),
file: z
.string()
.min(1)
.max(1024)
.optional()
.describe("Skill-relative supporting file. Defaults to SKILL.md when a skill is selected"),
})
.strict()
.refine(
({ file, offset, query, skill }) =>
skill ? query === undefined && offset === undefined : file === undefined,
"Provide a skill and optional file, or list skills with an optional query and offset.",
);
Loading
Loading