From 81b341baae29a8c59e1eb9530486ef3fa4b2109f Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Thu, 26 Nov 2026 12:07:17 -0600 Subject: [PATCH] refactor(core): parse MCP skill entries once and type skill load failures --- packages/core/src/mcp/client.ts | 23 ++++- packages/core/src/mcp/index.ts | 2 +- packages/core/src/plugin/mcp-skill.ts | 122 +++++++++++++++++++------- packages/core/src/skill.ts | 29 +++++- packages/core/test/mcp-skills.test.ts | 45 +++++++++- 5 files changed, 177 insertions(+), 44 deletions(-) diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index 19aeea50cbe..a90e48c71b6 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -29,7 +29,7 @@ import { type VersionNegotiationOptions, } from "@modelcontextprotocol/client" import type { CallToolResult as SdkCallToolResult } from "@modelcontextprotocol/client" -import { SKILLS_EXTENSION_ID, SkillsClient } from "@modelcontextprotocol/client/ext/skills" +import { SKILLS_EXTENSION_ID, SkillsClient, SkillVerificationError } from "@modelcontextprotocol/client/ext/skills" import type { Skill as SdkSkill, SkillFile as SdkSkillFile } from "@modelcontextprotocol/client/ext/skills" import { Cause, @@ -320,6 +320,13 @@ export interface Events { }) => Stream.Stream } +/** A skill file the server served doesn't match its entry: not listed, or a different size, digest or frontmatter. */ +export class SkillMismatchError extends Schema.TaggedError()("McpClient.SkillMismatchError", { + uri: Schema.String, + check: Schema.Literals(["unlisted", "size", "digest", "frontmatter"]), + message: Schema.String, +}) {} + /** Experimental: MCP Skills is a beta extension; may change without compatibility guarantees. */ export interface Skills { /** Every valid skill the server lists (`skills/list`); invalid entries are logged and skipped. No file is read. */ @@ -328,7 +335,7 @@ export interface Skills { * Reads one file of a listed skill, its `SKILL.md` when `ref` is omitted, and verifies its size, digest and, for * `SKILL.md`, frontmatter against the entry. */ - readonly read: (skill: Skill, ref?: string) => Effect.Effect + readonly read: (skill: Skill, ref?: string) => Effect.Effect /** One skill by its `SKILL.md` URI, listed or not (`skills/get`). No file is read. */ readonly get: (uri: string) => Effect.Effect } @@ -838,7 +845,17 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { Effect.map((result) => result.skills), ), read: (skill, ref) => - request("read MCP skill file", (signal) => skills.read(skill, ref, { signal, timeout: execution })), + Effect.tryPromise({ + try: (signal) => skills.read(skill, ref, { signal, timeout: execution }), + catch: (error) => + error instanceof SkillVerificationError + ? new SkillMismatchError({ uri: error.uri, check: error.reason, message: error.message }) + : failure(error), + }).pipe( + Effect.tapError((error) => + Effect.logWarning("failed to read MCP skill file", { server, error: error.message }), + ), + ), get: (uri) => request("get MCP skill", (signal) => skills.get(uri, { signal, timeout: execution })).pipe( Effect.map((result) => result.skill), diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index c09f1040494..b46d894b0c0 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -220,7 +220,7 @@ export interface Interface extends State.Transformable { readonly server: ServerName | string readonly entry: McpClient.Skill readonly ref?: string - }) => Effect.Effect + }) => Effect.Effect /** Experimental: one skill of a server by its `SKILL.md` URI, listed or not (`skills/get`). No file is read. */ readonly getSkill: (input: { readonly server: ServerName | string diff --git a/packages/core/src/plugin/mcp-skill.ts b/packages/core/src/plugin/mcp-skill.ts index b59858ec588..1bb17d8a2cf 100644 --- a/packages/core/src/plugin/mcp-skill.ts +++ b/packages/core/src/plugin/mcp-skill.ts @@ -4,7 +4,7 @@ import { define } from "@opencode/plugin/effect/plugin" import { Hash } from "@opencode/util/hash" import { Effect, Stream } from "effect" import { Bus } from "../bus.js" -import type { McpClient } from "../mcp/client.js" +import { McpClient } from "../mcp/client.js" import { Mcp } from "../mcp/index.js" import { AbsolutePath } from "../schema.js" import { Skill } from "../skill.js" @@ -22,9 +22,9 @@ export const Plugin = define({ const bus = yield* Bus.Service const skills = yield* Skill.Service const state = { - listed: yield* mcp.skills(), + listed: yield* accept(yield* mcp.skills()), // Skills servers confirmed by URI without listing them, until that server's skills change. - confirmed: [] as Mcp.Skill[], + confirmed: [] as Served[], // The ID each skill was registered under, by server and URI. registered: new Map(), } @@ -41,17 +41,17 @@ export const Plugin = define({ (error) => new Skill.LoadError({ skill: id, - message: `MCP server "${target.server}" did not confirm ${target.uri}: ${error.message}`, + reason: { _tag: "NotConfirmed", server: target.server, uri: target.uri, detail: error.message }, }), ), ) - state.confirmed.push({ server: Mcp.ServerName.make(target.server), entry }) + state.confirmed.push(...(yield* accept([{ server: Mcp.ServerName.make(target.server), entry }]))) yield* skills.reload() return state.registered.get(key(target.server, entry.uri)) }) const cache = new Map() - const read = (skill: Mcp.Skill, id: Skill.ID, digest: string, file?: string) => + const read = (skill: Served, id: Skill.ID, digest: string, file?: Skill.FilePath) => Effect.suspend(() => { // The SKILL.md key is separate because only a SKILL.md read carries the body without frontmatter. const key = file === undefined ? `${digest} SKILL.md` : digest @@ -63,7 +63,10 @@ export const Plugin = define({ (error) => new Skill.LoadError({ skill: id, - message: `Failed to load ${file ?? "SKILL.md"} of MCP skill ${id}: ${error.message}`, + reason: + error instanceof McpClient.SkillMismatchError + ? { _tag: "Mismatch", file: file ?? Skill.manifest, check: error.check } + : { _tag: "Unavailable", file: file ?? Skill.manifest, detail: error.message }, }), ), ) @@ -72,12 +75,13 @@ export const Plugin = define({ yield* bus.subscribe(Mcp.SkillsChanged).pipe( Stream.runForEach((event) => mcp.skills().pipe( - Effect.tap(() => - Effect.sync( - () => (state.confirmed = state.confirmed.filter((skill) => skill.server !== event.data.server)), - ), + Effect.flatMap(accept), + Effect.tap((listed) => + Effect.sync(() => { + state.confirmed = state.confirmed.filter((skill) => skill.server !== event.data.server) + state.listed = listed + }), ), - Effect.tap((listed) => Effect.sync(() => (state.listed = listed))), Effect.andThen(skills.reload()), ), ), @@ -93,34 +97,26 @@ export const Plugin = define({ id: Skill.ID.make(`${skill.server}:${path(skill.entry.uri).join(".")}`), })) for (const { skill, id } of [...ids(state.listed), ...confirmed]) { - // Dynamic skills list no files, so nothing they serve can be verified. - if (skill.entry.resources === "dynamic") continue if (!SkillDiscovery.isSafeSegment(id) || editor.get(id)) continue state.registered.set(key(skill.server, skill.entry.uri), id) - const root = skill.entry.uri.slice(0, skill.entry.uri.lastIndexOf("/") + 1) - const files = skill.entry.resources.flatMap((resource) => { - const file = resource.uri.startsWith(root) ? Skill.parseFilePath(resource.uri.slice(root.length)) : undefined - return file ? [{ file, digest: resource.digest }] : [] - }) - const digest = files.find((item) => item.file === Skill.manifest)?.digest ?? "" editor.add( { id, name: Skill.Name.make(id), - description: skill.entry.frontmatter.description, - path: AbsolutePath.make(Skill.uri(id, "SKILL.md")), + description: skill.description, + path: AbsolutePath.make(Skill.uri(id, Skill.manifest)), content: - cache.get(`${digest} SKILL.md`)?.body ?? - read(skill, id, digest).pipe( + cache.get(`${skill.manifest} SKILL.md`)?.body ?? + read(skill, id, skill.manifest).pipe( Effect.map((result) => result.body ?? ""), // Lists the loaded content from now on. Effect.tap(() => skills.reload()), ), }, Object.fromEntries( - files.map((item) => [ - item.file, - read(skill, id, item.digest, item.file).pipe(Effect.map((result) => result.bytes)), + Array.from(skill.files, ([file, digest]) => [ + file, + read(skill, id, digest, file).pipe(Effect.map((result) => result.bytes)), ]), ), { type: "mcp", server: skill.server }, @@ -130,19 +126,77 @@ export const Plugin = define({ }), }) +/** A skill a server serves, parsed from its entry. */ +export interface Served { + readonly server: Mcp.ServerName + /** The entry as listed, which every file read is checked against. */ + readonly entry: McpClient.Skill + readonly name: string + readonly description: string + /** The digest of its SKILL.md. */ + readonly manifest: string + /** Its other files, with their digests. */ + readonly files: ReadonlyMap +} + +export type Parsed = + | { readonly _tag: "Served"; readonly skill: Served } + | { readonly _tag: "Rejected"; readonly server: Mcp.ServerName; readonly uri: string; readonly reason: Rejection } + +/** Why an entry isn't registered: `dynamic` lists no files to check, and a skill needs a listed `SKILL.md`. */ +export type Rejection = "dynamic" | "no_manifest" + +/** + * Parses one entry a server lists into a skill whose files are known by path and digest. Files outside the skill's + * folder, or with paths that aren't safe, aren't part of it. + */ +export function parseEntry(skill: Mcp.Skill): Parsed { + const entry = skill.entry + const rejected = (reason: Rejection): Parsed => ({ _tag: "Rejected", server: skill.server, uri: entry.uri, reason }) + if (entry.resources === "dynamic") return rejected("dynamic") + const root = entry.uri.slice(0, entry.uri.lastIndexOf("/") + 1) + const listed = new Map( + entry.resources.flatMap((resource) => { + const file = resource.uri.startsWith(root) ? Skill.parseFilePath(resource.uri.slice(root.length)) : undefined + return file ? [[file, resource.digest] as const] : [] + }), + ) + const manifest = listed.get(Skill.manifest) + if (!manifest) return rejected("no_manifest") + listed.delete(Skill.manifest) + return { + _tag: "Served", + skill: { + server: skill.server, + entry, + name: entry.frontmatter.name, + description: entry.frontmatter.description, + manifest, + files: listed, + }, + } +} + +/** The entries that parse, logging the rest once with why. */ +const accept = (skills: ReadonlyArray) => + Effect.gen(function* () { + const parsed = skills.map(parseEntry) + yield* Effect.forEach( + parsed.flatMap((item) => (item._tag === "Rejected" ? [item] : [])), + (item) => Effect.logWarning("skipping MCP skill", { server: item.server, uri: item.uri, reason: item.reason }), + { discard: true }, + ) + return parsed.flatMap((item) => (item._tag === "Served" ? [item.skill] : [])) + }) + /** * `:` for each skill. Same-named skills of one server are told apart by the trailing segments of their * paths that differ, joined with `.`, which a skill name can't contain: `acme/billing/refunds` and * `acme/support/refunds` become `docs:billing.refunds` and `docs:support.refunds`. Paths that never differ, such as * one skill under two URI schemes, also get a hash of the URI. */ -function ids(listed: ReadonlyArray) { - return Array.from( - Map.groupBy( - listed.filter((skill) => skill.entry.resources !== "dynamic"), - (skill) => `${skill.server}:${skill.entry.frontmatter.name}`, - ), - ).flatMap(([id, group]) => { +function ids(listed: ReadonlyArray) { + return Array.from(Map.groupBy(listed, (skill) => `${skill.server}:${skill.name}`)).flatMap(([id, group]) => { if (group.length === 1) return group.map((skill) => ({ skill, id: Skill.ID.make(id) })) const segments = group.map((skill) => path(skill.entry.uri)) const longest = Math.max(...segments.map((parts) => parts.length)) diff --git a/packages/core/src/skill.ts b/packages/core/src/skill.ts index da5232eb99c..58a460bae92 100644 --- a/packages/core/src/skill.ts +++ b/packages/core/src/skill.ts @@ -40,10 +40,35 @@ export class FileNotFoundError extends Schema.TaggedError()(" file: Schema.String, }) {} +/** Why a skill or one of its files couldn't be loaded. */ +export const LoadReason = Schema.Union([ + /** The server failed or couldn't be reached. */ + Schema.TaggedStruct("Unavailable", { file: Schema.String, detail: Schema.String }), + /** The file the server served doesn't match what it listed. */ + Schema.TaggedStruct("Mismatch", { + file: Schema.String, + check: Schema.Literals(["unlisted", "size", "digest", "frontmatter"]), + }), + /** The server didn't confirm a skill named by address. */ + Schema.TaggedStruct("NotConfirmed", { server: Schema.String, uri: Schema.String, detail: Schema.String }), +]) +export type LoadReason = typeof LoadReason.Type + export class LoadError extends Schema.TaggedError()("Skill.LoadError", { skill: Schema.String, - message: Schema.String, -}) {} + reason: LoadReason, +}) { + override get message() { + switch (this.reason._tag) { + case "Unavailable": + return `Failed to load ${this.reason.file} of skill ${this.skill}: ${this.reason.detail}` + case "Mismatch": + return `Failed to load ${this.reason.file} of skill ${this.skill}: it doesn't match what the server listed (${this.reason.check})` + case "NotConfirmed": + return `MCP server "${this.reason.server}" did not confirm ${this.reason.uri}: ${this.reason.detail}` + } + } +} /** A skill's SKILL.md body or one of its files: inline, or loaded the first time it's needed. */ export type Content = string | Effect.Effect diff --git a/packages/core/test/mcp-skills.test.ts b/packages/core/test/mcp-skills.test.ts index 08d6c4becb1..2a5bb9acd62 100644 --- a/packages/core/test/mcp-skills.test.ts +++ b/packages/core/test/mcp-skills.test.ts @@ -1,4 +1,4 @@ -import { describe, expect } from "bun:test" +import { describe, expect, test } from "bun:test" import { McpServer, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server" import { skillEntry, SkillsExtension, type Skill as ServedSkill } from "@modelcontextprotocol/server/ext/skills" import { ConfigMCP } from "@opencode/schema/config/mcp" @@ -11,6 +11,7 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Environment } from "@opencode/core/environment/index" import { Integration } from "@opencode/core/integration" import { Location } from "@opencode/core/location" +import type { McpClient } from "@opencode/core/mcp/client" import { Mcp } from "@opencode/core/mcp/index" import { McpSkillPlugin } from "@opencode/core/plugin/mcp-skill" import { AbsolutePath } from "@opencode/core/schema" @@ -150,6 +151,39 @@ const connect = Effect.fnUntraced(function* (name: string, url: string, expected return yield* eventually(skills.list(), (listed) => expected.every((id) => listed.some((skill) => skill.id === id))) }) +describe("McpSkillPlugin.parseEntry", () => { + const server = Mcp.ServerName.make("team") + const entry = (resources: McpClient.Skill["resources"]): Mcp.Skill => ({ + server, + entry: { uri: "skill://acme/pdf/SKILL.md", frontmatter: { name: "pdf", description: "PDFs" }, resources }, + }) + const file = (path: string) => ({ uri: `skill://acme/pdf/${path}`, digest: `sha256:${path}`, size: 1 }) + + test("keeps SKILL.md's digest and the skill's other files by path", () => { + const parsed = McpSkillPlugin.parseEntry(entry([file("SKILL.md"), file("references/FORMS.md")])) + if (parsed._tag !== "Served") throw new Error("expected a served skill") + expect(parsed.skill.manifest).toBe("sha256:SKILL.md") + expect(Array.from(parsed.skill.files, ([path, digest]) => [String(path), digest])).toEqual([ + ["references/FORMS.md", "sha256:references/FORMS.md"], + ]) + }) + + test("leaves out files outside the skill's folder or with unsafe paths", () => { + const parsed = McpSkillPlugin.parseEntry( + entry([file("SKILL.md"), { uri: "skill://acme/other/x.md", digest: "sha256:x", size: 1 }, file("%2e%2e/secret")]), + ) + expect(parsed._tag === "Served" && parsed.skill.files.size).toBe(0) + }) + + test("rejects dynamic skills and skills that don't list SKILL.md", () => { + expect(McpSkillPlugin.parseEntry(entry("dynamic"))).toMatchObject({ _tag: "Rejected", reason: "dynamic" }) + expect(McpSkillPlugin.parseEntry(entry([file("references/FORMS.md")]))).toMatchObject({ + _tag: "Rejected", + reason: "no_manifest", + }) + }) +}) + describe("MCP skills", () => { it.live("lists skills as : without reading, and refuses dynamic ones", () => Effect.gen(function* () { @@ -246,10 +280,13 @@ describe("MCP skills", () => { const skills = yield* Skill.Service const content = yield* skills.content(id).pipe(Effect.flip) expect(content).toBeInstanceOf(Skill.LoadError) - expect(content.message).toStartWith("Failed to load SKILL.md of MCP skill team:deploy: ") - expect(content.message).toContain("digest") + expect(content.reason).toEqual({ _tag: "Mismatch", file: "SKILL.md", check: "digest" }) const file = yield* skills.read(id, script).pipe(Effect.flip) - expect(file.message).toContain("digest") + expect(file._tag === "Skill.LoadError" && file.reason).toEqual({ + _tag: "Mismatch", + file: "scripts/run.sh", + check: "digest", + }) }), )