From df79010bc6a36dc653b4fe9b024bd0d33bb06ac1 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:06:08 -0600 Subject: [PATCH] feat(core): load skills from MCP servers (#66201) --- packages/app/e2e/utils/mock-api.ts | 5 + packages/app/e2e/utils/mock-server.ts | 20 ++ packages/app/src/workspaces/files/model.tsx | 17 +- .../client/src/promise/generated/client.ts | 17 ++ .../client/src/promise/generated/types.ts | 13 + packages/client/test/promise.test.ts | 1 + packages/core/src/mcp/client.ts | 54 +++- packages/core/src/mcp/connection.ts | 30 ++- packages/core/src/mcp/index.ts | 48 +++- packages/core/src/mcp/pool.ts | 7 +- packages/core/src/plugin/internal.ts | 2 + packages/core/src/plugin/mcp-skill.ts | 90 +++++++ packages/core/src/skill.ts | 42 +++- packages/core/src/tool/plugin/read.ts | 23 +- packages/core/test/fixture/mcp.ts | 2 + packages/core/test/mcp-skills.test.ts | 232 ++++++++++++++++++ packages/core/test/skill.test.ts | 7 +- packages/protocol/openapi.json | 128 +++++++++- packages/protocol/src/client.ts | 1 + packages/protocol/src/errors.ts | 9 + packages/protocol/src/groups/skill.ts | 21 +- packages/schema/src/config/flag.ts | 2 + packages/schema/src/skill.ts | 4 +- packages/server/src/handlers/skill.ts | 28 ++- packages/server/test/skill.test.ts | 17 +- 25 files changed, 776 insertions(+), 44 deletions(-) create mode 100644 packages/core/src/plugin/mcp-skill.ts create mode 100644 packages/core/test/mcp-skills.test.ts diff --git a/packages/app/e2e/utils/mock-api.ts b/packages/app/e2e/utils/mock-api.ts index 545f62d94a2..4c16746763b 100644 --- a/packages/app/e2e/utils/mock-api.ts +++ b/packages/app/e2e/utils/mock-api.ts @@ -196,6 +196,11 @@ const Group = HttpApiGroup.make("mock") ) .add(HttpApiEndpoint.get("command", "/api/command", { success: Json })) .add(HttpApiEndpoint.get("skill", "/api/skill", { success: Json })) + .add( + HttpApiEndpoint.get("skillFile", "/api/experimental/skill/:skillID/file/*", { + success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()), + }), + ) .add(HttpApiEndpoint.get("plugin", "/api/plugin", { success: Json })) .add(HttpApiEndpoint.get("mcp", "/api/mcp", { success: Json })) .add( diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index 3794d30fb1a..624d288a45c 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -715,6 +715,26 @@ function mockHandlers( ) }), ) + // Serves a listed skill's inline content as its SKILL.md. + .handleRaw("skillFile", (ctx) => + Effect.sync(() => { + const path = `skill://${decodeURIComponent(new URL(ctx.request.url, "http://localhost").pathname.slice("/api/experimental/skill/".length)).replace("/file/", "/")}` + + const skill = resolve(config.skills ?? []).find( + (item) => Predicate.hasProperty(item, "path") && item.path === path, + ) + + if (Predicate.hasProperty(skill, "content") && Predicate.isString(skill.content)) + return HttpServerResponse.uint8Array(new TextEncoder().encode(skill.content)) + + return HttpServerResponse.jsonUnsafe( + // SAFETY: the server's wire body for a missing file, which the client decodes into its own error. + // oxlint-disable-next-line anti-slop-effect/no-manual-tagged-construction -- see SAFETY above + { _tag: "FileNotFoundError", path, message: `File not found: ${path}` }, + { status: 404 }, + ) + }), + ) // Raw, so a hook's answer can replace the status and body. .handleRaw("worktreeCreate", (ctx) => Effect.gen(function* () { diff --git a/packages/app/src/workspaces/files/model.tsx b/packages/app/src/workspaces/files/model.tsx index 3820fca3ab0..88fc2a86097 100644 --- a/packages/app/src/workspaces/files/model.tsx +++ b/packages/app/src/workspaces/files/model.tsx @@ -241,7 +241,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({ ) } - // Built-in and virtual skills register `skill://` (or legacy `/builtin/`) paths whose content is inline in `/api/skill`. + // Built-in and virtual skills register `skill://` (or legacy `/builtin/`) paths. const isVirtualSkill = (file: string) => file.startsWith("skill://") || file.startsWith("/builtin/") const builtinSkill = async (file: string, directory: string) => { @@ -252,10 +252,21 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({ return (data.location.skill.list({ directory }) ?? data.location.skill.list())?.find((item) => item.path === file) } - const readBuiltin = (file: string, directory: string): Promise => - builtinSkill(file, directory).then((skill) => + // `skill:///` reads through the server, which loads files a skill serves on demand. Legacy `/builtin/` + // skills keep their content inline in `/api/skill`. + const readBuiltin = (file: string, directory: string): Promise => { + if (file.startsWith("skill://")) { + const [skillID, ...rest] = file.slice("skill://".length).split("/") + + return serverSDK.api.experimental.skill + .file({ skillID, path: rest.join("/"), location: { directory } }) + .then((data) => fileContentFromBytes(file, data)) + } + + return builtinSkill(file, directory).then((skill) => skill ? { type: "text", content: skill.content, mimeType: artifactMime(file) } : undefined, ) + } const load = (input: string, options?: { force?: boolean; silent?: boolean }) => { const file = path.normalize(input) diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index af220c87eee..c62aaee95fb 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -211,6 +211,8 @@ import type { CommandListOutput, SkillListInput, SkillListOutput, + ExperimentalSkillFileInput, + ExperimentalSkillFileOutput, RpcCallInput, RpcCallOutput, EventSubscribeInput, @@ -1416,6 +1418,21 @@ export function make(options: ClientOptions) { requestOptions, ), }, + skill: { + file: (input: ExperimentalSkillFileInput, requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/experimental/skill/${encodeURIComponent(input.skillID)}/file/${encodePath(input.path)}`, + query: { location: input["location"] }, + successStatus: 200, + declaredStatuses: [400, 401, 404, 502], + empty: false, + binary: true, + }, + requestOptions, + ), + }, persistentPty: { read: (input: ExperimentalPersistentPtyReadInput, requestOptions?: RequestOptions) => request<{ readonly data: ExperimentalPersistentPtyReadOutput }>( diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 2918c586563..d82b751615d 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2675,6 +2675,7 @@ export type ConfigEntry = home_memory?: boolean project_overlay?: boolean opencode_api?: boolean + mcp_skills?: boolean sqlite_fts?: boolean video_generate?: boolean | { model?: string | { providerID: string; model: string; variant?: string } } part_rows?: boolean @@ -3347,6 +3348,10 @@ export type FileNotFoundError = { readonly _tag: "FileNotFoundError"; readonly p export const isFileNotFoundError = (value: unknown): value is FileNotFoundError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "FileNotFoundError" +export type SkillLoadError = { readonly _tag: "SkillLoadError"; readonly skill: string; readonly message: string } +export const isSkillLoadError = (value: unknown): value is SkillLoadError => + typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "SkillLoadError" + export type RpcError = { readonly _tag: "RpcError" readonly type: string @@ -4517,6 +4522,14 @@ export type SkillListInput = { readonly location?: { readonly directory?: string export type SkillListOutput = { location: LocationPublicRef; data: Array } +export type ExperimentalSkillFileInput = { + readonly skillID: string + readonly location?: { readonly directory?: string | undefined } | undefined + readonly path: string +} + +export type ExperimentalSkillFileOutput = globalThis.Uint8Array + export type RpcCallInput = { readonly rpcID: string readonly method: string diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 865dec8863a..9d81ca28243 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -59,6 +59,7 @@ test("exposes every standard HTTP API group", () => { "integration", "mcp", "file", + "skill", "persistentPty", "media", "blob", diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index 83841f50315..9292ac22876 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -29,6 +29,12 @@ import { type Transport, type VersionNegotiationOptions, } from "@modelcontextprotocol/client" +import { + SKILLS_EXTENSION_ID, + SkillsClient, + type Skill as SdkSkill, + type SkillFile as SdkSkillFile, +} from "@modelcontextprotocol/client/ext/skills" import { Cause, Clock, @@ -167,6 +173,9 @@ export type EventMessage = const EVENT_STREAM_REJECTED = new Set([-32601, -32602, -32023, -32024, -32026]) export type { GetPromptResult, Prompt, ReadResourceResult, Resource } +/** Experimental: MCP Skills is a beta extension; may change without compatibility guarantees. */ +export type Skill = SdkSkill +export type SkillFile = SdkSkillFile export type ResourceTemplate = ResourceTemplateType /** A listed tool, keeping the server's fields except `icons`, each only when it has the right type. */ @@ -279,6 +288,8 @@ export interface Connection { ) => Effect.Effect /** MCP Events, when the connection declared them and negotiated 2026-07-28 with a server that offers them. Experimental; see `Events`. */ readonly events: Events | undefined + /** MCP Skills, when the server offers them with resources. Experimental; see `Skills`. */ + readonly skills: Skills | undefined readonly onClose: (callback: (reason: string) => void) => void readonly onSessionExpired: (callback: () => void) => void readonly onToolsChanged: (callback: () => void) => void @@ -313,6 +324,17 @@ export interface Events { }) => Stream.Stream } +/** 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. */ + readonly list: () => Effect.Effect, Error> + /** + * 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 +} + /** An MCP server reached over a transport someone else already opened, such as a client socket. */ export interface Attached { readonly type: "attached" @@ -334,6 +356,8 @@ export interface ConnectOptions { readonly roots?: boolean /** Experimental: declares MCP Events, a beta extension, and exposes `Connection.events` for a 2026-07-28 server that offers them. */ readonly events?: boolean + /** Experimental: declares MCP Skills, a beta extension, and exposes `Connection.skills` for a server that offers them. */ + readonly skills?: boolean } /** @@ -410,7 +434,14 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { // Legacy era only: roots are deprecated as of 2026-07-28 and modern servers cannot request them. // Some legacy servers refuse to run without one (https://github.com/anomalyco/opencode/issues/2308). ...(options.roots === false ? {} : { roots: {} }), - ...(options.events ? { extensions: { [EVENTS]: {} } } : {}), + ...(options.events || options.skills + ? { + extensions: { + ...(options.events ? { [EVENTS]: {} } : {}), + ...(options.skills ? { [SKILLS_EXTENSION_ID]: {} } : {}), + }, + } + : {}), }, versionNegotiation: negotiation(protocol, timeout?.startup ?? DEFAULT_STARTUP_TIMEOUT), listChanged: { @@ -693,6 +724,9 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { if (!known.arguments(input.arguments ?? {})) return yield* reject(-32602, `Arguments for ${input.name} do not match its inputSchema`) }) + // MCP Skills (SEP-2640), a beta extension, serves skill files as resources. + const skills = + options.skills && advertised("resources") ? new SkillsClient(client, { skipInvalid: true }) : undefined // Annotated rather than `satisfies`: the inferred SDK types are cyclic, so declaration emit needs the named type. const connection: Connection = { @@ -786,6 +820,24 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { ), } : undefined, + skills: skills?.supported + ? { + list: () => + list("list MCP skills", (signal) => skills.list({}, { ...catalog, signal })).pipe( + Effect.tap((result) => + Effect.forEach( + result.invalid, + (entry) => + Effect.logWarning("skipping invalid MCP skill", { server, uri: entry.uri, reason: entry.reason }), + { discard: true }, + ), + ), + Effect.map((result) => result.skills), + ), + read: (skill, ref) => + request("read MCP skill file", (signal) => skills.read(skill, ref, { signal, timeout: execution })), + } + : undefined, // Tool lists skip the SDK response cache: it re-stringifies every list, and on the first tools/call // re-parses it and compiles an output validator for every listed tool. Each call passes its own // checked definition instead, so modern Mcp-Param-* header mirroring still sees the input schema. diff --git a/packages/core/src/mcp/connection.ts b/packages/core/src/mcp/connection.ts index 14aa07eafa2..8fbac4c64b1 100644 --- a/packages/core/src/mcp/connection.ts +++ b/packages/core/src/mcp/connection.ts @@ -10,8 +10,8 @@ import type { McpClient } from "./client.js" export type Failure = Extract -/** A catalog the server can change: its tools, prompts or resources. */ -export type Kind = "tools" | "prompts" | "resources" +/** A catalog the server can change: its tools, prompts, resources or skills. */ +export type Kind = "tools" | "prompts" | "resources" | "skills" // Unshared connections to one remote endpoint, from any number of Locations, take turns at their // handshake so the endpoint does not receive a startup burst. @@ -51,6 +51,8 @@ export interface Input { */ readonly shared?: boolean readonly clientInfo?: { readonly name: string; readonly version: string } + /** Lists the server's MCP Skills when it offers them. */ + readonly skills?: boolean /** Read on every attempt, so a credential change applies to the next one. */ readonly authProvider: Effect.Effect readonly elicitation: McpClient.ElicitationHandler @@ -80,6 +82,8 @@ export interface Connection { /** The server's tool list as listed. Each refresh replaces the array. */ readonly tools: ReadonlyArray | undefined readonly prompts: ReadonlyArray | undefined + /** The server's skill entries as listed, when it offers MCP Skills. Each refresh replaces the array. */ + readonly skills: ReadonlyArray | undefined /** Connects and lists tools; a failure is reported through `failed`. */ readonly start: Effect.Effect readonly stop: Effect.Effect @@ -100,6 +104,7 @@ export function make(input: Input): Connection { client?: McpClient.Connection tools?: ReadonlyArray prompts?: ReadonlyArray + skills?: ReadonlyArray } = {} // Runs a connection callback under the lock, dropping it if the connection is no longer the live @@ -126,6 +131,16 @@ export function make(input: Input): Connection { Effect.andThen(input.events.changed("prompts")), ) + const refreshSkills = (client: McpClient.Connection) => + client.skills + ? client.skills.list().pipe( + Effect.map((skills) => { + state.skills = skills + }), + Effect.andThen(input.events.changed("skills")), + ) + : Effect.void + // Re-establishes a connection whose HTTP session the server dropped, unless another path already // replaced it while this one waited for the lock. const recover = (client: McpClient.Connection) => @@ -156,7 +171,8 @@ export function make(input: Input): Connection { client.onSessionExpired(() => input.fork(recover(client))) client.onToolsChanged(() => live(refreshTools(client).pipe(Effect.andThen(input.events.changed("tools"))))) client.onPromptsChanged(() => live(refreshPrompts(client))) - client.onResourcesChanged(() => live(input.events.changed("resources"))) + // MCP Skills announces a changed skill list as a resource list change. + client.onResourcesChanged(() => live(input.events.changed("resources").pipe(Effect.andThen(refreshSkills(client))))) } const start: Effect.Effect = Effect.suspend(() => @@ -185,6 +201,7 @@ export function make(input: Input): Connection { clientInfo: input.clientInfo, roots: !input.shared, events: true, + skills: input.skills, }).pipe( Effect.flatMap( (client): Effect.Effect<{ client: McpClient.Connection; tools?: ReadonlyArray }, Error> => @@ -207,9 +224,11 @@ export function make(input: Input): Connection { state.client = result.value.client state.tools = result.value.tools state.prompts = [] + state.skills = [] watch(result.value.client) yield* input.events.connected whenLive(result.value.client)(refreshPrompts(result.value.client)) + whenLive(result.value.client)(refreshSkills(result.value.client)) return } yield* Scope.close(scope, Exit.void) @@ -234,10 +253,12 @@ export function make(input: Input): Connection { state.client = undefined state.tools = undefined state.prompts = undefined + state.skills = undefined yield* Scope.close(scope, Exit.void) yield* input.events.changed("tools") yield* input.events.changed("resources") yield* input.events.changed("prompts") + yield* input.events.changed("skills") }) return { @@ -250,6 +271,9 @@ export function make(input: Input): Connection { get prompts() { return state.prompts }, + get skills() { + return state.skills + }, start, stop, recovering, diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index b4f63228616..68b65ba2344 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -31,6 +31,7 @@ import { httpFetch } from "@opencode/util/effect/app-node-platform" import { Credential } from "../credential.js" import { Bus } from "../bus.js" import { Environment } from "../environment/index.js" +import { Flag } from "../flag.js" import { Form } from "../form.js" import { Integration } from "../integration.js" import { KeyedMutex } from "../effect/keyed-mutex.js" @@ -47,6 +48,8 @@ import { McpPool } from "./pool.js" export const ServerName = Schema.String.pipe(Schema.brand("MCP.ServerName")) export type ServerName = typeof ServerName.Type export const PromptsChanged = ephemeral({ type: "mcp.prompts.changed", schema: { server: Schema.String } }) +/** Experimental: a server's MCP Skills list changed. */ +export const SkillsChanged = ephemeral({ type: "mcp.skills.changed", schema: { server: Schema.String } }) export const Status = Mcp.Status export type Status = Mcp.Status @@ -63,6 +66,11 @@ export type ToolResultContent = McpClient.CallToolContent export type ToolResult = McpClient.CallToolResult export type Prompt = McpClient.Prompt & { readonly server: ServerName } export type PromptResult = McpClient.GetPromptResult +/** Experimental: a skill entry a server lists through MCP Skills, a beta extension. */ +export interface Skill { + readonly server: ServerName + readonly entry: McpClient.Skill +} export const Resource = Mcp.Resource export type Resource = Mcp.Resource @@ -134,7 +142,12 @@ const FALLBACK_LIST_TIMEOUT = "5 seconds" const GLOBAL_ELICITATION_SESSION_ID = "global" const URL_ELICITATION_FIELD_KEY = "elicitation" -const changes = { tools: McpEvent.ToolsChanged, resources: McpEvent.ResourcesChanged, prompts: PromptsChanged } +const changes = { + tools: McpEvent.ToolsChanged, + resources: McpEvent.ResourcesChanged, + prompts: PromptsChanged, + skills: SkillsChanged, +} // Event IDs a subscription remembers to skip a duplicate the server replays. const SEEN_EVENTS = 100 @@ -197,6 +210,17 @@ export interface Interface extends State.Transformable { readonly server: ServerName | string readonly uri: string }) => Effect.Effect + /** Experimental: skills that connected servers list through MCP Skills. */ + readonly skills: () => Effect.Effect + /** + * Experimental: reads one verified file of a skill from the server that listed it, its `SKILL.md` when `ref` is + * omitted. + */ + readonly readSkill: (input: { + readonly server: ServerName | string + readonly entry: McpClient.Skill + readonly ref?: string + }) => Effect.Effect /** Experimental: MCP Events of a connected server that offers them. */ readonly events: (server: ServerName | string) => Effect.Effect /** @@ -363,6 +387,7 @@ export const layer = (options?: Options) => Effect.gen(function* () { const location = yield* Location.Service const environment = yield* Environment.Service + const skills = yield* Flag.enabled("mcp_skills") const bus = yield* Bus.Service const forms = yield* Form.Service const integration = yield* Integration.Service @@ -673,6 +698,7 @@ export const layer = (options?: Options) => config, directory: location.directory, clientInfo: options?.clientInfo, + skills, authProvider: Effect.suspend(() => selectCredential(entry).pipe(Effect.flatMap((credential) => connectProvider(name, entry, credential))), ), @@ -702,6 +728,7 @@ export const layer = (options?: Options) => yield* bus.publish(McpEvent.ToolsChanged, { server: name }) yield* bus.publish(McpEvent.ResourcesChanged, { server: name }) yield* bus.publish(PromptsChanged, { server: name }) + yield* bus.publish(SkillsChanged, { server: name }) yield* bus.publish(McpEvent.StatusChanged, { server: name }) }), failed: (failure) => @@ -1092,7 +1119,8 @@ export const layer = (options?: Options) => return Array.from(entries) .flatMap(([server, entry]) => { const instructions = entry.connection.client?.instructions - if (!instructions) return [] + // A server that offers skills says what it needs to in them. Dynamic skills aren't registered. + if (!instructions || entry.connection.skills?.some((skill) => skill.resources !== "dynamic")) return [] return [{ server, instructions }] }) .toSorted((a, b) => a.server.localeCompare(b.server)) @@ -1150,6 +1178,21 @@ export const layer = (options?: Options) => ), }) }), + skills: Effect.fn("MCP.skills")(function* () { + return Array.from(entries).flatMap(([server, entry]) => + (entry.connection.skills ?? []).map((skill): Skill => ({ server, entry: skill })), + ) + }), + readSkill: Effect.fn("MCP.readSkill")(function* (input) { + const name = ServerName.make(input.server) + const target = yield* connected(name) + if (!target.client) return yield* Effect.fail(new Error(unavailable(name, target.entry.status))) + return yield* target.entry.connection.recovering(target.client, (connection) => + connection.skills + ? connection.skills.read(input.entry, input.ref) + : Effect.fail(new Error(`MCP server "${name}" does not offer skills`)), + ) + }), events: Effect.fn("MCP.events")(function* (server) { return (yield* connected(ServerName.make(server))).client?.events }), @@ -1217,6 +1260,7 @@ export function configured(options?: Options) { Form.node, Integration.node, Credential.node, + Flag.node, httpFetch, McpPool.node, ], diff --git a/packages/core/src/mcp/pool.ts b/packages/core/src/mcp/pool.ts index 233fe4bc799..9e55f831a69 100644 --- a/packages/core/src/mcp/pool.ts +++ b/packages/core/src/mcp/pool.ts @@ -51,9 +51,10 @@ export const key = (input: { /** The active OAuth credential's ID, which a token refresh keeps and a sign-in replaces. */ readonly credential?: string readonly clientInfo?: { readonly name: string; readonly version: string } + readonly skills?: boolean }) => { const config = input.config - const common = [config.protocol, config.timeout ?? null, input.clientInfo ?? null] + const common = [config.protocol, config.timeout ?? null, input.clientInfo ?? null, input.skills ?? false] if (config.type === "remote") return JSON.stringify([ "remote", @@ -343,6 +344,9 @@ export const layer = Layer.effect( get prompts() { return live().prompts }, + get skills() { + return live().skills + }, start: Effect.gen(function* () { if (input.config.type === "local" && input.config.cwd === undefined && !unfixed.has(input.name)) { unfixed.add(input.name) @@ -365,6 +369,7 @@ export const layer = Layer.effect( yield* input.events.changed("tools") yield* input.events.changed("resources") yield* input.events.changed("prompts") + yield* input.events.changed("skills") }), recovering: (client, request) => state.shared diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index 2b167a4fea8..ab6570540a5 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -123,6 +123,7 @@ import { DynamicProviderPlugin } from "./provider/dynamic.js" import { OpencodePlugin } from "./provider/opencode.js" import { WebSearchPlugins } from "./websearch/index.js" import { SkillPlugin } from "./skill.js" +import { McpSkillPlugin } from "./mcp-skill.js" import { VcsHgPlugin } from "./vcs/hg.js" import { ToolInputRepairPlugin } from "./tool-input-repair.js" import { OptimizePlugin } from "./optimize.js" @@ -327,6 +328,7 @@ const post = [ ConfigToolOutputPlugin.Plugin, ConfigCompatibilityPlugin.Plugin, ConfigSkillPlugin.Plugin, + McpSkillPlugin.Plugin, ConfigProviderPlugin.Plugin, // Run the dynamic npm SDK loader after SDK, instance, and external plugins register their `sdk` hooks. DynamicProviderPlugin, diff --git a/packages/core/src/plugin/mcp-skill.ts b/packages/core/src/plugin/mcp-skill.ts new file mode 100644 index 00000000000..b43190c1363 --- /dev/null +++ b/packages/core/src/plugin/mcp-skill.ts @@ -0,0 +1,90 @@ +export * as McpSkillPlugin from "./mcp-skill.js" + +import { define } from "@opencode/plugin/effect/plugin" +import { Effect, Stream } from "effect" +import { Bus } from "../bus.js" +import type { McpClient } from "../mcp/client.js" +import { Mcp } from "../mcp/index.js" +import { AbsolutePath } from "../schema.js" +import { Skill } from "../skill.js" +import { SkillDiscovery } from "../skill/discovery.js" + +/** + * Registers the skills connected MCP servers list as `:`. Nothing is read until a skill or one of its + * files is used, and the MCP client checks every file it reads against the listed size and digest. Verified files are + * kept in memory by digest, so a skill whose SKILL.md was loaded once lists its content. + */ +export const Plugin = define({ + id: "opencode.mcp.skill", + effect: Effect.fn(function* () { + const mcp = yield* Mcp.Service + const bus = yield* Bus.Service + const skills = yield* Skill.Service + const state = { listed: yield* mcp.skills() } + const cache = new Map() + + const read = (skill: Mcp.Skill, id: Skill.ID, digest: string, file?: string) => + 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 + const cached = cache.get(key) + if (cached) return Effect.succeed(cached) + return mcp.readSkill({ server: skill.server, entry: skill.entry, ref: file }).pipe( + Effect.tap((result) => Effect.sync(() => cache.set(key, result))), + Effect.mapError( + (error) => + new Skill.LoadError({ + skill: id, + message: `Failed to load ${file ?? "SKILL.md"} of MCP skill ${id}: ${error.message}`, + }), + ), + ) + }) + + yield* bus.subscribe(Mcp.SkillsChanged).pipe( + Stream.runForEach(() => + mcp.skills().pipe( + Effect.tap((listed) => Effect.sync(() => (state.listed = listed))), + Effect.andThen(skills.reload()), + ), + ), + Effect.forkScoped({ startImmediately: true }), + ) + + yield* skills.transform((editor) => { + for (const skill of state.listed) { + // Dynamic skills list no files, so nothing they serve can be verified. + if (skill.entry.resources === "dynamic") continue + const id = Skill.ID.make(`${skill.server}:${skill.entry.frontmatter.name}`) + if (!SkillDiscovery.isSafeSegment(id) || editor.get(id)) continue + 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) ? resource.uri.slice(root.length) : "" + return SkillDiscovery.isSafeRelativePath(file) ? [{ file, digest: resource.digest }] : [] + }) + const digest = files.find((item) => item.file === "SKILL.md")?.digest ?? "" + editor.add( + { + id, + name: Skill.Name.make(id), + description: skill.entry.frontmatter.description, + path: AbsolutePath.make(Skill.uri(id, "SKILL.md")), + content: + cache.get(`${digest} SKILL.md`)?.body ?? + read(skill, id, digest).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)), + ]), + ), + ) + } + }) + }), +}) diff --git a/packages/core/src/skill.ts b/packages/core/src/skill.ts index e308ec6ec55..06e45e0e115 100644 --- a/packages/core/src/skill.ts +++ b/packages/core/src/skill.ts @@ -30,6 +30,15 @@ export type Name = Skill.Name export { Event } from "@opencode/schema/skill" +export class NotFoundError extends Schema.TaggedError()("Skill.NotFoundError", { + skill: Schema.String, +}) {} + +export class FileNotFoundError extends Schema.TaggedError()("Skill.FileNotFoundError", { + skill: Schema.String, + file: Schema.String, +}) {} + export class LoadError extends Schema.TaggedError()("Skill.LoadError", { skill: Schema.String, message: Schema.String, @@ -123,8 +132,11 @@ export interface Interface extends State.Transformable { readonly content: (id: ID) => Effect.Effect /** Paths of the skill's virtual files besides SKILL.md. */ readonly files: (id: ID) => Effect.Effect | undefined> - /** One virtual file, loaded when it isn't inline. */ - readonly file: (id: ID, file: string) => Effect.Effect + /** + * One file of a skill by its path relative to the skill's folder, loaded when it isn't inline. `SKILL.md` is the + * body without frontmatter. Any path that isn't one of the skill's files, unsafe ones included, is not found. + */ + readonly read: (id: ID, file: string) => Effect.Effect readonly list: () => Effect.Effect } @@ -183,29 +195,33 @@ const layer = Layer.effect( ), }) + const content = Effect.fn("Skill.content")(function* (id: ID) { + const current = state.get() + const loader = current.loaders.get(id) + const inline = current.skills.get(id)?.content ?? "" + if (inline || !loader) return inline + return yield* loader + }) + return Service.of({ transform: state.transform, reload: state.reload, get: Effect.fn("Skill.get")(function* (id) { return state.get().skills.get(id) }), - content: Effect.fn("Skill.content")(function* (id) { - const current = state.get() - const loader = current.loaders.get(id) - const content = current.skills.get(id)?.content ?? "" - if (content || !loader) return content - return yield* loader - }), + content, files: Effect.fn("Skill.files")(function* (id) { const current = state.get() if (!current.skills.has(id)) return undefined return Array.from(current.files.get(id)?.keys() ?? []) }), - file: Effect.fn("Skill.file")(function* (id, file) { + read: Effect.fn("Skill.read")(function* (id, file) { const current = state.get() - const value = current.skills.has(id) ? current.files.get(id)?.get(file) : undefined - if (value === undefined || typeof value === "string" || value instanceof Uint8Array) return value - return yield* value + if (!current.skills.has(id)) return yield* new NotFoundError({ skill: id }) + const value = file === "SKILL.md" ? yield* content(id) : current.files.get(id)?.get(file) + if (value === undefined) return yield* new FileNotFoundError({ skill: id, file }) + const loaded = typeof value === "string" || value instanceof Uint8Array ? value : yield* value + return typeof loaded === "string" ? new TextEncoder().encode(loaded) : loaded }), list: Effect.fn("Skill.list")(function* () { return Array.from(state.get().skills.values()) diff --git a/packages/core/src/tool/plugin/read.ts b/packages/core/src/tool/plugin/read.ts index dfdec7270a9..a80cacacf66 100644 --- a/packages/core/src/tool/plugin/read.ts +++ b/packages/core/src/tool/plugin/read.ts @@ -94,26 +94,21 @@ export const Plugin = { ...Permission.invocation(context), }) const virtualFs = Environment.makeFiles(Environment.makeMemoryDriver()) - const encoder = new TextEncoder() // Only the requested file is loaded. The rest stay empty, which is enough for directory listings. - const load = (file: string) => { - if (file !== parsed.target.slice(1)) return Effect.succeed("") - if (file === "SKILL.md") return skills.content(id) - return skills.file(id, file).pipe(Effect.map((value) => value ?? "")) - } yield* Effect.forEach( files, (file) => - load(file).pipe( + (file === parsed.target.slice(1) ? skills.read(id, file) : Effect.succeed(new Uint8Array())).pipe( Effect.mapError( - (error) => new ToolFailure({ message: `Unable to read ${input.path}: ${error.message}` }), - ), - Effect.flatMap((value) => - virtualFs.write( - AbsolutePath.make(`/${file}`), - typeof value === "string" ? encoder.encode(value) : value, - ), + (error) => + new ToolFailure({ + message: + error._tag === "Skill.LoadError" + ? `Unable to read ${input.path}: ${error.message}` + : `File not found: ${input.path}`, + }), ), + Effect.flatMap((bytes) => virtualFs.write(AbsolutePath.make(`/${file}`), bytes)), ), { discard: true }, ) diff --git a/packages/core/test/fixture/mcp.ts b/packages/core/test/fixture/mcp.ts index 2d0c15860d6..60ff7d4f047 100644 --- a/packages/core/test/fixture/mcp.ts +++ b/packages/core/test/fixture/mcp.ts @@ -24,6 +24,8 @@ export const emptyMcp = Mcp.Service.of({ resourceCatalog: () => Effect.succeed(Mcp.ResourceCatalog.make({ resources: [], templates: [] })), resources: () => Effect.succeed(Mcp.ResourceCatalog.make({ resources: [], templates: [] })), readResource: () => Effect.undefined, + skills: () => Effect.succeed([]), + readSkill: () => Effect.die("unused mcp.readSkill"), events: () => Effect.undefined, follow: () => Stream.die("unused Mcp.follow"), subscribe: () => Effect.die("unused Mcp.subscribe"), diff --git a/packages/core/test/mcp-skills.test.ts b/packages/core/test/mcp-skills.test.ts new file mode 100644 index 00000000000..ba61f21b5ec --- /dev/null +++ b/packages/core/test/mcp-skills.test.ts @@ -0,0 +1,232 @@ +import { describe, expect } 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" +import { Document, Info } from "@opencode/schema/config" +import { Bus } from "@opencode/core/bus" +import { Config } from "@opencode/core/config" +import { Flag } from "@opencode/core/flag" +import { Credential } from "@opencode/core/credential" +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 { Mcp } from "@opencode/core/mcp/index" +import { McpSkillPlugin } from "@opencode/core/plugin/mcp-skill" +import { AbsolutePath } from "@opencode/core/schema" +import { Skill } from "@opencode/core/skill" +import { makeLocationNode } from "@opencode/util/effect/app-node" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { isRecord } from "@opencode/util/record" +import { Effect, Layer } from "effect" +import { hostEnvironmentLayer } from "./fixture/environment" +import { tempLocationLayer } from "./fixture/location" +import { host } from "./plugin/host" +import { testEffect } from "./lib/effect" +import { eventually } from "./lib/eventually" + +const unused = () => Effect.die("unused integration service") +const config = Config.testLayer([new Document({ type: "document", info: new Info({}) })]) +const it = testEffect( + AppNodeBuilder.build( + LayerNode.group([ + Mcp.node, + Skill.node, + Bus.node, + makeLocationNode({ + name: "test/mcp-skills-plugin", + layer: Layer.effectDiscard(McpSkillPlugin.Plugin.effect(host())), + deps: [Mcp.node, Bus.node, Skill.node], + }), + ]), + [ + Config.node.replace(config), + Flag.node.replace(Flag.testLayer([], { overrides: "mcp_skills" })), + Location.node.replace(tempLocationLayer), + Environment.node.replace(hostEnvironmentLayer), + Integration.node.replace( + Layer.mock(Integration.Service, { + revision: () => 0, + connection: { + active: unused, + resolve: unused, + key: unused, + external: unused, + activate: unused, + update: unused, + remove: unused, + status: unused, + }, + oauth: { connect: unused, status: unused, complete: unused, cancel: unused }, + command: { connect: unused, status: unused, cancel: unused }, + }), + ), + Credential.node.replace(Layer.mock(Credential.Service, {})), + ], + ).pipe(Layer.provideMerge(config)), +) + +const DEPLOY = "---\nname: deploy\ndescription: Deploy the app\n---\n# Deploy\n\nRun scripts/run.sh.\n" +const deploy = { "SKILL.md": DEPLOY, "scripts/run.sh": "echo run" } +const id = Skill.ID.make("team:deploy") + +/** + * A Streamable HTTP MCP server publishing skills through the SDK's skills extension. Keys are skill folders below + * `skill://`, each mapping file paths to contents; `serve` changes what a file read returns. Records every + * `resources/read` and the client's declared capabilities. + */ +const skillServer = ( + skills: Record>, + options: { instructions?: string; extra?: ServedSkill[] } = {}, +) => + Effect.acquireRelease( + Effect.promise(async () => { + const entries = [ + ...(await Promise.all(Object.entries(skills).map(([folder, files]) => skillEntry(folder, files)))), + ...(options.extra ?? []), + ] + const served = new Map( + Object.entries(skills).flatMap(([folder, files]) => + Object.entries(files).map(([file, content]) => [`skill://${folder}/${file}`, content] as const), + ), + ) + const state = { reads: [] as string[], capabilities: undefined as unknown } + const server = new McpServer({ name: "team", version: "1.0.0" }, { instructions: options.instructions }) + new SkillsExtension({ + source: { + list: async () => ({ skills: entries }), + get: async (uri) => entries.find((entry) => entry.uri === uri), + read: async (uri) => { + const text = served.get(uri) + return text === undefined ? undefined : { text } + }, + }, + }).attach(server) + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: () => crypto.randomUUID(), + enableJsonResponse: true, + }) + await server.connect(transport) + const http = Bun.serve({ + port: 0, + fetch: async (request) => { + const body: unknown = request.method === "POST" ? await request.clone().json() : undefined + if (isRecord(body) && isRecord(body.params)) { + if (body.method === "resources/read" && typeof body.params.uri === "string") + state.reads.push(body.params.uri) + if (body.method === "initialize") state.capabilities = body.params.capabilities + } + return transport.handleRequest(request) + }, + }) + return { + url: http.url.toString(), + state, + serve: (uri: string, content: string) => served.set(uri, content), + close: async () => { + await server.close().catch(() => {}) + await http.stop(true) + }, + } + }), + (server) => Effect.promise(server.close), + ) + +const connect = Effect.fnUntraced(function* (name: string, url: string, expected: ReadonlyArray) { + const mcp = yield* Mcp.Service + const skills = yield* Skill.Service + yield* mcp.add(name, new ConfigMCP.Remote({ type: "remote", url, oauth: false })) + yield* eventually(mcp.servers(), (servers) => + servers.some((server) => server.name === name && server.status.status === "connected"), + ) + return yield* eventually(skills.list(), (listed) => expected.every((id) => listed.some((skill) => skill.id === id))) +}) + +describe("MCP skills", () => { + it.live("lists skills as : without reading, and refuses dynamic ones", () => + Effect.gen(function* () { + const server = yield* skillServer( + { deploy }, + { + extra: [ + { + uri: "skill://live/SKILL.md", + frontmatter: { name: "live", description: "Generated" }, + resources: "dynamic", + }, + ], + }, + ) + const listed = yield* connect("team", server.url, ["team:deploy"]) + expect(server.state.capabilities).toMatchObject({ extensions: { "io.modelcontextprotocol/skills": {} } }) + expect(listed).toEqual([ + { + id, + name: Skill.Name.make("team:deploy"), + description: "Deploy the app", + path: AbsolutePath.make(Skill.uri(id, "SKILL.md")), + content: "", + }, + ]) + const skills = yield* Skill.Service + expect(yield* skills.files(id)).toEqual(["scripts/run.sh"]) + expect(server.state.reads).toEqual([]) + }), + ) + + it.live("loads verified files on demand and reuses them by digest", () => + Effect.gen(function* () { + const server = yield* skillServer({ deploy }) + yield* connect("team", server.url, ["team:deploy"]) + const skills = yield* Skill.Service + expect(yield* skills.content(id)).toBe("# Deploy\n\nRun scripts/run.sh.\n") + expect(new TextDecoder().decode(yield* skills.read(id, "scripts/run.sh"))).toBe("echo run") + // Once loaded, the content is listed and nothing is read again. + yield* eventually(skills.get(id), (skill) => skill?.content === "# Deploy\n\nRun scripts/run.sh.\n") + yield* skills.content(id) + yield* skills.read(id, "scripts/run.sh") + expect(server.state.reads).toEqual(["skill://deploy/SKILL.md", "skill://deploy/scripts/run.sh"]) + }), + ) + + it.live("fails a load whose digest does not match the listing", () => + Effect.gen(function* () { + const server = yield* skillServer({ deploy }) + yield* connect("team", server.url, ["team:deploy"]) + // Same size, other bytes. + server.serve("skill://deploy/scripts/run.sh", "echo ran") + server.serve("skill://deploy/SKILL.md", DEPLOY.replace("Run", "Ran")) + 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") + const file = yield* skills.read(id, "scripts/run.sh").pipe(Effect.flip) + expect(file.message).toContain("digest") + }), + ) + + it.live("leaves out the instructions of servers that offer skills", () => + Effect.gen(function* () { + const withSkills = yield* skillServer({ deploy }, { instructions: "Use the deploy skill." }) + // Dynamic skills aren't registered, so they don't replace instructions. + const without = yield* skillServer( + {}, + { + instructions: "Call ping.", + extra: [ + { + uri: "skill://live/SKILL.md", + frontmatter: { name: "live", description: "Generated" }, + resources: "dynamic", + }, + ], + }, + ) + yield* connect("team", withSkills.url, ["team:deploy"]) + yield* connect("other", without.url, []) + const mcp = yield* Mcp.Service + expect(yield* mcp.instructions()).toEqual([{ server: Mcp.ServerName.make("other"), instructions: "Call ping." }]) + }), + ) +}) diff --git a/packages/core/test/skill.test.ts b/packages/core/test/skill.test.ts index 3a54e4c4c0c..7b326532437 100644 --- a/packages/core/test/skill.test.ts +++ b/packages/core/test/skill.test.ts @@ -227,7 +227,7 @@ describe("Skill", () => { expect(yield* skill.files(id)).toEqual(["references/a.md", "references/b.md"]) expect(loaded).toEqual([]) expect(yield* skill.content(id)).toBe("# remote") - expect(yield* skill.file(id, "references/a.md")).toBe("A") + expect(new TextDecoder().decode(yield* skill.read(id, "references/a.md"))).toBe("A") expect(loaded).toEqual(["SKILL.md", "references/a.md"]) }), ) @@ -265,7 +265,10 @@ describe("Skill", () => { const files = yield* skill.files(Skill.ID.make("review")) expect(files).toEqual(["references/a.md", "references/b.md"]) - expect(yield* skill.file(Skill.ID.make("review"), "references/a.md")).toBe("A") + expect(new TextDecoder().decode(yield* skill.read(Skill.ID.make("review"), "references/a.md"))).toBe("A") + expect((yield* skill.read(Skill.ID.make("review"), "../secret").pipe(Effect.flip))._tag).toBe( + "Skill.FileNotFoundError", + ) const fs = yield* FSUtil.Service const prepared = yield* Skill.prepare( { ...fs, scan: () => Effect.die(new Error("unexpected disk scan")) }, diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index dfbc821ffdf..20808356ecd 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -10236,6 +10236,111 @@ "summary": "List skills" } }, + "/api/experimental/skill/{skillID}/file/*": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.skill.file", + "parameters": [ + { + "name": "skillID", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Skill.ID" + }, + "required": true + }, + { + "name": "location", + "in": "query", + "schema": { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Absolute path of the directory." + } + }, + "additionalProperties": false + }, + "required": false, + "description": "Location to run the request in, sent as location[directory]. Omit to use the server's default location." + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "404": { + "description": "SkillNotFoundError | FileNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/SkillNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/FileNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "502": { + "description": "SkillLoadError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SkillLoadErrorEncoded" + } + } + } + } + }, + "description": "Read one file of a skill, loading it when the skill serves it on demand. SKILL.md returns the body without frontmatter. Experimental: may change without compatibility guarantees.", + "summary": "Read skill file" + } + }, "/api/rpc/{rpcID}/{method}": { "post": { "tags": ["rpc"], @@ -17887,6 +17992,9 @@ "opencode_api": { "type": "boolean" }, + "mcp_skills": { + "type": "boolean" + }, "sqlite_fts": { "type": "boolean" }, @@ -26249,7 +26357,8 @@ "$ref": "#/components/schemas/AbsolutePath" }, "content": { - "type": "string" + "type": "string", + "description": "The SKILL.md body. Empty for a skill whose body loads on demand, such as an MCP skill." } }, "required": ["id", "name", "path", "content"], @@ -26258,6 +26367,23 @@ "Skill.Name": { "type": "string" }, + "SkillLoadErrorEncoded": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": ["SkillLoadError"] + }, + "skill": { + "$ref": "#/components/schemas/Skill.ID" + }, + "message": { + "type": "string" + } + }, + "required": ["_tag", "skill", "message"], + "additionalProperties": false + }, "SkillNotFoundErrorEncoded": { "type": "object", "properties": { diff --git a/packages/protocol/src/client.ts b/packages/protocol/src/client.ts index e6a8d02df2b..a39bc048d46 100644 --- a/packages/protocol/src/client.ts +++ b/packages/protocol/src/client.ts @@ -118,6 +118,7 @@ export const effectOmitEndpoints = new Set([ "media.get", "blob.get", "artifacts.view", + "skill.file", "pty.connect", "persistentPty.connect", "mcp.client", diff --git a/packages/protocol/src/errors.ts b/packages/protocol/src/errors.ts index 3731251efc9..55033f040bd 100644 --- a/packages/protocol/src/errors.ts +++ b/packages/protocol/src/errors.ts @@ -181,6 +181,15 @@ export class SkillNotFoundError extends Schema.TaggedError() { httpApiStatus: 404 }, ) {} +export class SkillLoadError extends Schema.TaggedError()( + "SkillLoadError", + { + skill: Skill.ID, + message: Schema.String, + }, + { httpApiStatus: 502 }, +) {} + export class McpServerNotFoundError extends Schema.TaggedError()( "McpServerNotFoundError", { diff --git a/packages/protocol/src/groups/skill.ts b/packages/protocol/src/groups/skill.ts index b01bf265d4d..a9b3aad8d54 100644 --- a/packages/protocol/src/groups/skill.ts +++ b/packages/protocol/src/groups/skill.ts @@ -1,7 +1,8 @@ import { Skill } from "@opencode/schema/skill" import { Location } from "@opencode/schema/location" import { Schema } from "effect" -import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api" +import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api" +import { FileNotFoundError, SkillLoadError, SkillNotFoundError } from "../errors.js" import { LocationQuery, locationQueryOpenApi } from "./location.js" export const SkillGroup = HttpApiGroup.make("server.skill") @@ -19,6 +20,24 @@ export const SkillGroup = HttpApiGroup.make("server.skill") }), ), ) + .add( + HttpApiEndpoint.get("skill.file", "/api/experimental/skill/:skillID/file/*", { + params: { skillID: Skill.ID }, + query: LocationQuery, + success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()), + error: [SkillNotFoundError, FileNotFoundError, SkillLoadError], + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "experimental.skill.file", + summary: "Read skill file", + description: + "Read one file of a skill, loading it when the skill serves it on demand. SKILL.md returns the body without frontmatter. Experimental: may change without compatibility guarantees.", + transform: (operation) => ({ ...operation, tags: ["experimental"] }), + }), + ), + ) .annotateMerge( OpenApi.annotations({ title: "skill", diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index e14c2c67c2e..1943e63071b 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -24,6 +24,8 @@ export const registry = { "Load a personal config dir for each project from ~/.config/opencode/project//, read like an extra .opencode dir that ranks above the repo's own, and let home memory keep the skills it builds for the user there.", opencode_api: 'Let Code Mode scripts call the OpenCode HTTP API with fetch("opencode:///api/..."), in-process and already signed in, with no permission checks. Only in local and dev builds, and off there until you opt in with OPENCODE_FLAGS=opencode_api or experimental.opencode_api: true.', + mcp_skills: + "Load skills from MCP servers that offer them (the io.modelcontextprotocol/skills extension), named :. A server that offers skills no longer has its instructions included.", sqlite_fts: "Build an SQLite full-text index of session titles and message text in the background, and enable the opencode.session.search and opencode.session.read tools. The index covers every session in the database and starts while any loaded location enables it; SQLite keeps it current from then on, also after this is turned off.", } as const satisfies Record diff --git a/packages/schema/src/skill.ts b/packages/schema/src/skill.ts index a731cb85b28..aebf07af3fb 100644 --- a/packages/schema/src/skill.ts +++ b/packages/schema/src/skill.ts @@ -30,7 +30,9 @@ export const Info = Schema.Struct({ description: Schema.String.pipe(optional), autoinvoke: Schema.Boolean.pipe(optional), path: AbsolutePath, - content: Schema.String, + content: Schema.String.annotate({ + description: "The SKILL.md body. Empty for a skill whose body loads on demand, such as an MCP skill.", + }), }).annotate({ identifier: "Skill.Info" }) const Updated = ephemeral({ type: "skill.updated", schema: {} }) diff --git a/packages/server/src/handlers/skill.ts b/packages/server/src/handlers/skill.ts index 39039fcd638..ab994ccab71 100644 --- a/packages/server/src/handlers/skill.ts +++ b/packages/server/src/handlers/skill.ts @@ -1,8 +1,34 @@ import { Skill } from "@opencode/core/skill" +import { FileNotFoundError, SkillLoadError, SkillNotFoundError } from "@opencode/protocol/errors" +import { Effect } from "effect" import { HttpApiBuilder } from "effect/http-api" import { Api } from "../api" import { response } from "../location" export const SkillHandler = HttpApiBuilder.group(Api, "server.skill", (handlers) => - handlers.handle("skill.list", () => response(Skill.Service.use((skill) => skill.list()))), + handlers + .handle("skill.list", () => response(Skill.Service.use((skill) => skill.list()))) + .handle("skill.file", (ctx) => + Effect.gen(function* () { + const skills = yield* Skill.Service + // The path after /api/experimental/skill//file/. + const raw = new URL(ctx.request.url, "http://localhost").pathname.split("/").slice(6).join("/") + const file = yield* Effect.try({ + try: () => decodeURIComponent(raw), + catch: () => new FileNotFoundError({ path: raw, message: `File not found: ${raw}` }), + }) + return yield* skills.read(ctx.params.skillID, file).pipe( + Effect.catchTags({ + "Skill.NotFoundError": (error) => + Effect.fail( + new SkillNotFoundError({ skill: ctx.params.skillID, message: `Skill not found: ${error.skill}` }), + ), + "Skill.FileNotFoundError": (error) => + Effect.fail(new FileNotFoundError({ path: error.file, message: `File not found: ${error.file}` })), + "Skill.LoadError": (error) => + Effect.fail(new SkillLoadError({ skill: ctx.params.skillID, message: error.message })), + }), + ) + }), + ), ) diff --git a/packages/server/test/skill.test.ts b/packages/server/test/skill.test.ts index c2df82b048c..7ea84061c04 100644 --- a/packages/server/test/skill.test.ts +++ b/packages/server/test/skill.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from "../../core/test/fixture/tmpdir" import { it } from "../../core/test/lib/effect" import { serveRoutes } from "./fixture/routes" -it.live("lists configured skills", () => +it.live("lists configured skills and reads their files", () => Effect.gen(function* () { const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-skill-endpoint-"))) yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, "skills", "demo"), { recursive: true })) @@ -34,6 +34,21 @@ it.live("lists configured skills", () => const body: unknown = yield* Effect.promise(() => response.json()) if (!isRecord(body) || !Array.isArray(body["data"])) throw new Error("Expected a skill list response") expect(body["data"].some((skill) => isRecord(skill) && skill["name"] === "demo")).toBeTrue() + + const file = (id: string, name: string) => { + const url = new URL(`/api/experimental/skill/${id}/file/${name}`, "http://opencode.local") + url.searchParams.set("location[directory]", tmp.path) + return Effect.promise(() => server.fetch(url)) + } + const found = yield* file("demo", "SKILL.md") + expect(found.status).toBe(200) + expect(yield* Effect.promise(() => found.text())).toBe("body\n") + const missingFile = yield* file("demo", "other.md") + expect(missingFile.status).toBe(404) + expect(yield* Effect.promise(() => missingFile.json())).toMatchObject({ _tag: "FileNotFoundError" }) + const missingSkill = yield* file("missing", "SKILL.md") + expect(missingSkill.status).toBe(404) + expect(yield* Effect.promise(() => missingSkill.json())).toMatchObject({ _tag: "SkillNotFoundError" }) }), )