The Open Framework for Building Agents
feat(eve): serve agent skills over mcpChannel (SEP-2640) (#4234)
Rui279e2b6a8119
diff --git a/.changeset/mcp-channel-skills.md b/.changeset/mcp-channel-skills.mdnew file mode 100644index 000000000..74f181b6d--- /dev/null+++ b/.changeset/mcp-channel-skills.md@@ -0,0 +1,7 @@+---+"eve": patch+---++`mcpChannel({ skills: true })` serves the agent's skills as SEP-2640 skills under `skill://`, with each file's size and SHA-256 digest. Files are served byte for byte, except that a `SKILL.md` without conforming `name` and `description` frontmatter is served with generated frontmatter. Channel routes also get `listSkillFiles(skill)`, which lists a skill's files with their sizes, and `readSkill(skill, path?)`, which returns one skill file's bytes; `describe()` lists each skill's name and description.++Production builds now ship skill files as eve-owned server assets and drop Nitro's default `server` asset entry, which bundled the app's `assets/` directory. An app that read `assets:server` storage in production finds it empty; eve reads only its own asset bases.diff --git a/.oxfmtrc.json b/.oxfmtrc.jsonindex 8c6f3ce87..b639f1d1e 100644--- a/.oxfmtrc.json+++ b/.oxfmtrc.json@@ -4,6 +4,7 @@"packages/eve/CHANGELOG.md","packages/eve/src/internal/testing/channel-conformance/MATRIX.md","apps/docs/registry.json",- "packages/eve/src/setup/scaffold/create/web-template.ts"+ "packages/eve/src/setup/scaffold/create/web-template.ts",+ "e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/references/latin1.md"]}diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex 103d71cd8..b21151a26 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -67,11 +67,14 @@ Each route receives these operation surfaces:- `attachSession(sessionId)` creates an I/O-free handle pinned to one durable session ID.- `to(channel, target).send(message, options)` hands work to another authored channel.- `params`, `waitUntil`, and `requestIp` provide request metadata and lifetime control.-- `describe()` returns the agent's name, description, and the compiled tools a caller can run outside a turn, with their JSON schemas, sorted by name. It carries no paths, config, or other inspection detail, so a channel can publish it to its callers. Tools that need a turn (framework tools, workflow and provider tools, tools without `execute`) and tools added by dynamic resolvers or subagents are left out.+- `describe()` returns the agent's name, description, the compiled tools a caller can run outside a turn, with their JSON schemas, and the compiled skills, each with its `name` and `description`, sorted by name. It reads the compiled manifest only, never a skill file, and carries no other paths, config, or inspection detail, so a channel can publish it to its callers. Tools that need a turn (framework tools, workflow and provider tools, tools without `execute`) and tools and skills added by dynamic resolvers or subagents are left out.- `invokeTool(name, input, { auth })` runs one of those tools as `auth`, outside any conversation: no model, turn, or workflow run. Each call gets its own session. Authored state starts from its initial value and is not kept, and a sandbox the tool opens is deleted when the call ends. It resolves to `completed` with the tool's output, or to `invalid-input`, `denied`, `failed`, `approval-required` when the tool's approval policy asks a person (the tool did not run), or `authorization-required` with the connections the tool needs a sign-in to.A direct call doesn't go through the AI SDK, so AI SDK telemetry integrations never see it. Conversation tool calls do: an integration that an `agent/instrumentation/*.ts` module registers with `registerTelemetry()` from `ai` receives `onToolExecutionStart` and `onToolExecutionEnd` for each of them. A direct call is traced by eve itself instead. It gets an `execute_tool` span under the caller's trace and emits `tool.call.started` and `tool.call.completed` to instrumentation. Over MCP, the caller's trace comes from the request's `_meta` trace context (see [Trace context](./mcp#trace-context)).+- `listSkillFiles(skill)` resolves to the skill's regular files, each with its `path` under the skill root and its `size` in bytes, sorted by path. It rejects a skill the agent does not have.+- `readSkill(skill, path?)` resolves to one skill file's raw bytes as a `Uint8Array`; decode text yourself, for example with `new TextDecoder().decode(bytes)`. `path` is relative to the skill root, such as `references/api.md`, and defaults to the skill's `SKILL.md`. It rejects absolute paths, paths with `.`, `..`, or empty segments, files the skill does not list, and files over 512 KiB.+Event handlers receive `(eventData, channel, ctx)`. `ctx.session.id` identifiesthe exact session, while `channel.continuation` exposes the current address and`alias()` when this channel needs to add another address. `session.failed`diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdxindex c1128b114..2e732cb94 100644--- a/docs/channels/mcp.mdx+++ b/docs/channels/mcp.mdx@@ -3,7 +3,7 @@ title: "MCP Channel"description: "Publish an eve agent as an MCP server with auth support."----The MCP channel lets clients such as Claude Code delegate durable work to an eve agent through four tools: `agent_start`, `agent_get`, `agent_update`, and `agent_cancel`. It can also publish the agent's own tools, so a client calls them directly; see [Publish the agent's tools](#publish-the-agents-tools).+The MCP channel lets clients such as Claude Code delegate durable work to an eve agent through four tools: `agent_start`, `agent_get`, `agent_update`, and `agent_cancel`. It can also publish the agent's own tools, so a client calls them directly, and its skills, so a client reads them; see [Publish the agent's tools](#publish-the-agents-tools) and [Publish the agent's skills](#publish-the-agents-skills).Use an [MCP connection](../connections/mcp) instead when your eve agent needs to call someone else's MCP server.@@ -225,7 +225,7 @@ export default mcpChannel({});```-`tools/list` returns the `agent_*` tools first, then the agent's tools in name order with their input and output JSON schemas. Framework tools, workflow and provider tools, tools without `execute`, and tools added by dynamic resolvers or subagents are not published. While `agent` is on, an agent tool named `agent_start`, `agent_get`, `agent_update`, or `agent_cancel` is not published, and eve logs a warning. With `agent: false`, the channel sends no `agent_*` instructions. Turning off both `agent` and `tools` throws.+`tools/list` returns the `agent_*` tools first, then the agent's tools in name order with their input and output JSON schemas. Framework tools, workflow and provider tools, tools without `execute`, and tools added by dynamic resolvers or subagents are not published. While `agent` is on, an agent tool named `agent_start`, `agent_get`, `agent_update`, or `agent_cancel` is not published, and eve logs a warning. With `agent: false`, the channel sends no `agent_*` instructions. Turning off `agent`, `tools`, and `skills` all at once throws, since the channel would publish nothing.Each `tools/call` checks the arguments against the tool's input schema, then runs the tool as the route-authenticated caller, or as a [forwarded user](#forwarded-principals), with no model, turn, or workflow run. Every caller the channel's `auth` admits can call these tools, outside the agent's instructions, so review what becomes callable before you turn this on. Each call gets its own session:@@ -277,6 +277,33 @@ The predicate receives the verified forwarder and the principals it asserts, as| The channel has no `trustedForwarders` | `403` || The predicate throws | `500` |+## Publish the agent's skills++Set `skills: true` to serve the agent's skills as [SEP-2640](https://modelcontextprotocol.io/seps/2640) skills under `skill://`, so a client that calls the agent's tools can also read the workflow knowledge behind them:++```ts title="agent/channels/mcp.ts"+import { localDev } from "eve/channels/auth";+import { mcpChannel } from "eve/channels/mcp";++export default mcpChannel({+ auth: localDev(),+ skills: true,+ tools: true,+});+```++The channel declares the `io.modelcontextprotocol/skills` extension and serves `skills/list`, `skills/get`, `resources/list`, `resources/templates/list`, `resources/read`, and `resources/directory/read`. Every caller the channel's `auth` admits can read every served skill. Each skill's entry is `skill://<name>/SKILL.md`, and its `resources` list every file with its `size` in bytes and a `sha256:` digest. `resources/list` returns one resource per served skill, its `SKILL.md`; the other files of a skill are reachable through `resources/directory/read` and the entry's `resources`, not listed there. `resources/directory/read` lists every directory of a skill, including empty ones, which return no children. `resources/templates/list` is always empty. `resources/read` returns UTF-8 text as `text` and anything else, such as images or Latin-1 files, as a base64 `blob`, byte for byte. Every skill and resource method carries the same cache hint as `tools/list`: private, for 5 minutes. The server's `resources` capability declares `listChanged: false`; eve never sends `notifications/resources/list_changed`, so a client re-reads after the hint expires. For each compiled artifact version, eve builds each skill's catalog snapshot once, listing its files and reading them to compute their sizes and digests. Only the served `SKILL.md` is kept in memory; `resources/read` reads other files from storage again, and a file removed since the snapshot is an unknown resource (`-32602`).++A skill is served whole or not at all. eve leaves a skill out of every method, and logs one warning naming the reason, when:++- its `SKILL.md` frontmatter does not meet the Agent Skills format: a `name` of up to 64 lowercase letters, digits, and single hyphens, and a `description` of 1 to 1024 characters;+- it has more than 512 files or more than 16 MiB in total;+- any of its files is over 512 KiB, unreadable, or has a path that cannot be a `skill://` URI.++A `SKILL.md` whose frontmatter already names the skill and has a `description` is served as authored. Otherwise, as for flat `.md` and module skills, eve serves it with frontmatter that carries the skill's name and description, and the digest describes that served document. Skills added by dynamic resolvers or subagents are not served.++Production builds ship skill files as eve-owned server assets, so they count toward the deployed function's size. `eve build` also drops Nitro's default `server` server-asset entry, the one that would bundle the app's `assets/` directory; eve reads only its own asset bases, and a route that reads `assets:server` storage finds it empty in production.+## Invocation ownershipEvery MCP operation reruns the configured auth policy. With authenticated policies, an invocation belongs to the principal that started it; knowing its ID is not sufficient. Bearer tokens are not stored with the invocation or forwarded to the agent's tools.diff --git a/e2e/fixtures/agent-mcp/agent/channels/mcp.ts b/e2e/fixtures/agent-mcp/agent/channels/mcp.tsindex ef8329e15..41022bc18 100644--- a/e2e/fixtures/agent-mcp/agent/channels/mcp.ts+++ b/e2e/fixtures/agent-mcp/agent/channels/mcp.ts@@ -12,6 +12,7 @@ export default mcpChannel({principalType: "service",}: null,+ skills: true,tools: true,// The loopback connection forwards the turn's user; only this service may.trustedForwarders: (forwarder) =>diff --git a/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/SKILL.md b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/SKILL.mdnew file mode 100644index 000000000..be5118085--- /dev/null+++ b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/SKILL.md@@ -0,0 +1,8 @@+---+name: kennel-handbook+description: Front-desk handbook for the Maple Street kennel, with its reference files.+---++# Kennel handbook++The files under `references/` and `assets/` are served byte for byte.diff --git a/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/assets/logo.png b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/assets/logo.pngnew file mode 100644index 000000000..08cd6f2bfBinary files /dev/null and b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/assets/logo.png differdiff --git a/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/references/empty.md b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/references/empty.mdnew file mode 100644index 000000000..e69de29bbdiff --git a/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/references/latin1.md b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/references/latin1.mdnew file mode 100644index 000000000..6f83395d9--- /dev/null+++ b/e2e/fixtures/agent-mcp/agent/skills/kennel-handbook/references/latin1.md@@ -0,0 +1 @@+caf�diff --git a/e2e/fixtures/agent-mcp/evals/skill-files.eval.ts b/e2e/fixtures/agent-mcp/evals/skill-files.eval.tsnew file mode 100644index 000000000..fef0605fb--- /dev/null+++ b/e2e/fixtures/agent-mcp/evals/skill-files.eval.ts@@ -0,0 +1,67 @@+import { readFile } from "node:fs/promises";+import { join } from "node:path";++import { defineEval } from "eve/evals";+import { equals } from "eve/evals/expect";++import { MCP_PATH, SERVICE_TOKEN } from "../fixture";++const SKILL = "kennel-handbook";+const PROTOCOL_VERSION = "2026-07-28";++/**+ * Files a bundler or asset store would alter if it handled them by name: a+ * PNG, an empty file, and Markdown that is not valid UTF-8.+ */+const FILES = ["assets/logo.png", "references/empty.md", "references/latin1.md"];++export default defineEval({+ description:+ "Alice's front-desk client reads the kennel handbook's files over MCP and gets them byte for byte, whatever their encoding.",++ async test(t) {+ for (const path of FILES) {+ // `eve eval` runs with the fixture as cwd, so this is the authored file.+ const authored = await readFile(join(process.cwd(), "agent/skills", SKILL, path));+ const uri = `skill://${SKILL}/${path}`;+ const response = await t.target.fetch(MCP_PATH, {+ body: JSON.stringify({+ id: 1,+ jsonrpc: "2.0",+ method: "resources/read",+ params: {+ uri,+ _meta: {+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": { name: "front-desk", version: "0.0.0" },+ "io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,+ },+ },+ }),+ headers: {+ accept: "application/json, text/event-stream",+ authorization: `Bearer ${SERVICE_TOKEN}`,+ "content-type": "application/json",+ "mcp-method": "resources/read",+ "mcp-name": uri,+ "mcp-protocol-version": PROTOCOL_VERSION,+ },+ method: "POST",+ });+ const body = (await response.json()) as {+ readonly result?: {+ readonly contents?: { readonly blob?: string; readonly text?: string }[];+ };+ };+ const [content] = body.result?.contents ?? [];+ const served =+ content?.blob !== undefined+ ? Buffer.from(content.blob, "base64")+ : Buffer.from(content?.text ?? "\u0000missing", "utf8");+ await t.require(+ { path, bytes: served.toString("hex") },+ equals({ path, bytes: authored.toString("hex") }),+ );+ }+ },+});diff --git a/e2e/fixtures/agent-mcp/fixture.ts b/e2e/fixtures/agent-mcp/fixture.tsindex 6057cd5c3..b1b4e5829 100644--- a/e2e/fixtures/agent-mcp/fixture.ts+++ b/e2e/fixtures/agent-mcp/fixture.ts@@ -16,7 +16,7 @@ export const SERVICE_TOKEN = "agent-mcp-fixture-service-token";/** The connection the agent uses to reach its own MCP channel. */export const LOOPBACK_CONNECTION = "loopback";-const MCP_PATH = "/eve/v1/mcp";+export const MCP_PATH = "/eve/v1/mcp";/** This deployment's MCP channel, the way `kennelUrl()` reaches its own kennel. */export function selfMcpUrl(): string {diff --git a/packages/eve/extension-contracts/compatibility/channel/v49.ts b/packages/eve/extension-contracts/compatibility/channel/v49.tsnew file mode 100644index 000000000..cfe64ec0a--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v49.ts@@ -0,0 +1,14 @@+import { defineChannel, GET } from "#public/channels/index.js";++// Epoch 49 route args had describe and invokeTool but no listSkillFiles or readSkill.+export default defineChannel({+ routes: [+ GET("/status", async (_request, { describe, invokeTool }) => {+ const { tools } = await describe();+ return Response.json({+ tools: tools.length,+ canInvokeTools: typeof invokeTool === "function",+ });+ }),+ ],+});diff --git a/packages/eve/extension-contracts/reports/channel/v50.json b/packages/eve/extension-contracts/reports/channel/v50.jsonnew file mode 100644index 000000000..144f4ff46--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v50.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 50,+ "sha256": "cf3050ea4f7be720c93facb73458991ac810e402c370239e27403a3d33ee0f0b",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs b/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjsindex 8d86b86d9..80637c35e 100644--- a/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs+++ b/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs@@ -14,6 +14,8 @@ export interface CallToolRequest {};}+export type McpJsonObject = Readonly<Record<string, unknown>>;+export interface McpRequestHandlerExtra {readonly mcpReq: {readonly signal: AbortSignal;@@ -51,10 +53,35 @@ export interface StandardSchemaWithJSON<TInput = unknown, TOutput = TInput> {};}+export interface StandardSchemaV1<TInput = unknown, TOutput = TInput> {+ readonly "~standard": {+ readonly version: 1;+ readonly vendor: string;+ readonly types?: { readonly input: TInput; readonly output: TOutput };+ };+}++export interface CacheHint {+ readonly cacheScope?: "private" | "public";+ readonly ttlMs?: number;+}++export type CacheableResultMethod =+ | "prompts/list"+ | "resources/list"+ | "resources/read"+ | "resources/templates/list"+ | "server/discover"+ | "tools/list";++export interface McpServerOptions {+ readonly cacheHints?: Partial<Record<CacheableResultMethod, CacheHint>>;+ readonly capabilities?: McpJsonObject;+ readonly instructions?: string;+}+export declare class Server {- constructor(info: { readonly name: string; readonly version: string }, options?: {- readonly capabilities?: Readonly<Record<string, unknown>>;- });+ constructor(info: { readonly name: string; readonly version: string }, options?: McpServerOptions);setRequestHandler<Result>(method: "tools/list",handler: (@@ -69,13 +96,25 @@ export declare class Server {context: McpRequestHandlerExtra,) => Result | Promise<Result>,): void;+ /** Spec methods validated by the SDK's own wire schemas. */+ setRequestHandler<Result>(+ method: "resources/list" | "resources/read" | "resources/templates/list",+ handler: (+ request: { readonly params?: McpJsonObject },+ context: McpRequestHandlerExtra,+ ) => Result | Promise<Result>,+ ): void;+ /** Custom (non-spec) methods: params are validated by the given schema. */+ setRequestHandler<TParams, Result>(+ method: string,+ schemas: { readonly params: StandardSchemaV1<unknown, TParams> },+ handler: (params: TParams, context: McpRequestHandlerExtra) => Result | Promise<Result>,+ ): void;}export declare class McpServer {- constructor(info: { readonly name: string; readonly version: string }, options?: {- readonly capabilities?: Readonly<Record<string, unknown>>;- readonly instructions?: string;- });+ readonly server: Server;+ constructor(info: { readonly name: string; readonly version: string }, options?: McpServerOptions);registerTool<TInput = unknown, TOutput = TInput>(name: string,config: {@@ -91,6 +130,24 @@ export declare class McpServer {): void;}+export declare class ProtocolError extends Error {+ constructor(code: number, message: string, data?: unknown);+ readonly code: number;+ readonly data?: unknown;+}++export declare const ProtocolErrorCode: {+ readonly InternalError: -32603;+ readonly InvalidParams: -32602;+ readonly InvalidRequest: -32600;+ readonly MethodNotFound: -32601;+};++/** A resource miss, with data \`{ uri }\`. */+export declare class ResourceNotFoundError extends ProtocolError {+ constructor(uri: string, message?: string);+}+export interface McpRequestContext {readonly era: "legacy" | "modern";readonly requestInfo: Request;diff --git a/packages/eve/src/channel/agent-description.test.ts b/packages/eve/src/channel/agent-description.test.tsindex cbac98111..5f35dd8d7 100644--- a/packages/eve/src/channel/agent-description.test.ts+++ b/packages/eve/src/channel/agent-description.test.ts@@ -1,6 +1,17 @@-import { expect, it } from "vitest";+import { describe, expect, it } from "vitest";-import { describeCompiledAgent } from "#channel/agent-description.js";+import {+ createAgentDescriptionRouteArgs,+ describeCompiledAgent,+ loadDescribedAgent,+} from "#channel/agent-description.js";+import { compileFromMemory } from "#internal/testing/compile-from-memory.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { withBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";+import {+ getActiveRuntimeSession,+ setRuntimeSessionCompiledArtifacts,+} from "#runtime/sessions/runtime-session.js";it("describes only the tools invokeTool can run, sorted by name", () => {const tool = (name: string, extra: Record<string, unknown> = {}) => ({@@ -21,6 +32,10 @@ it("describes only the tools invokeTool can run, sorted by name", () => {"source:remote": { owner: { kind: "application" } },},config: { description: "Runs the kennel.", name: "kennel" },+ skills: [+ { description: "Second.", files: [], name: "b" },+ { description: "First.", name: "a" },+ ],tools: [tool("lookup", { outputSchema: { type: "object" } }),tool("deploy", { requiresApproval: true }),@@ -30,6 +45,7 @@ it("describes only the tools invokeTool can run, sorted by name", () => {],};+ // Skills carry their name and description only; files come from `listSkillFiles`.expect(describeCompiledAgent(manifest as never)).toEqual({description: "Runs the kennel.",name: "kennel",@@ -48,5 +64,72 @@ it("describes only the tools invokeTool can run, sorted by name", () => {outputSchema: { type: "object" },},],+ skills: [+ { description: "First.", name: "a" },+ { description: "Second.", name: "b" },+ ],+ });+});++describe("loadDescribedAgent", () => {+ const source = createBundledRuntimeCompiledArtifactsSource();+ const compile = async (name: string, skills: readonly string[] = []) => {+ const { manifest, moduleMap } = await compileFromMemory({+ agentRoot: "/tmp/app/agent",+ appRoot: "/tmp/app",+ model: "openai/gpt-5.4",+ name,+ skills: skills.map((skill) => ({+ description: `About ${skill}.`,+ markdown: `# ${skill}\n`,+ name: skill,+ })),+ });+ return {+ manifest: {+ ...manifest,+ skills: manifest.skills.map(({ files: _files, ...skill }) => skill),+ },+ moduleMap,+ };+ };++ it("describes without touching skill files, and lists them only on request", async () => {+ const compiled = await compile("kennel", ["handbook"]);+ await withBundledCompiledArtifacts(compiled, async () => {+ const { args } = createAgentDescriptionRouteArgs(() => source);+ // A bundled build without `eve build`'s skill assets has no skill storage.+ await expect(args.describe()).resolves.toMatchObject({+ name: "kennel",+ skills: [{ description: "About handbook.", name: "handbook" }],+ });+ await expect(args.listSkillFiles("handbook")).rejects.toMatchObject({+ code: "unavailable",+ });+ await expect(args.listSkillFiles("other")).rejects.toMatchObject({ code: "unknown-skill" });+ await expect(args.readSkill("other")).rejects.toMatchObject({ code: "unknown-skill" });+ });+ });++ it("caches per runtime session and reloads when the installed snapshot changes", async () => {+ const [first, second, third] = await Promise.all([+ compile("first"),+ compile("second"),+ compile("third"),+ ]);+ await withBundledCompiledArtifacts(first, async () => {+ const described = await loadDescribedAgent(source);+ expect(described.description.name).toBe("first");+ expect(await loadDescribedAgent(source)).toBe(described);++ await withBundledCompiledArtifacts(second, async () => {+ expect((await loadDescribedAgent(source)).description.name).toBe("second");+ });+ expect(await loadDescribedAgent(source)).toBe(described);++ // Replace the snapshot inside this scoped session, as a redeploy would.+ setRuntimeSessionCompiledArtifacts(getActiveRuntimeSession(), third);+ expect((await loadDescribedAgent(source)).description.name).toBe("third");+ });});});diff --git a/packages/eve/src/channel/agent-description.ts b/packages/eve/src/channel/agent-description.tsindex 639eb70cc..7bf6be7f8 100644--- a/packages/eve/src/channel/agent-description.ts+++ b/packages/eve/src/channel/agent-description.ts@@ -1,7 +1,19 @@import type { CompiledAgentManifest, CompiledToolDefinition } from "#compiler/manifest.js";+import {+ comparePaths,+ createCompiledSkillFileSource,+ readSkillFile,+ type SkillFileSource,+ SkillReadError,+} from "#channel/skill-files.js";import { isInvocableCompiledTool } from "#channel/tool-eligibility.js";-import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";+import {+ getRuntimeCompiledArtifactsCacheKey,+ type RuntimeCompiledArtifactsSource,+} from "#runtime/compiled-artifacts-source.js";import { loadCompiledManifest } from "#runtime/loaders/manifest.js";+import { getActiveRuntimeSession } from "#runtime/sessions/runtime-session.js";import type { JsonObject } from "#shared/json.js";/** One compiled tool a caller can invoke outside a turn. */@@ -14,31 +26,118 @@ export interface AgentToolDescription {readonly approval: boolean;}+/** One file of a skill, as `listSkillFiles` returns it. `readSkill` rejects files over 512 KiB. */+export interface AgentSkillFileDescription {+ /** `/`-separated path under the skill root, e.g. `references/api.md`. */+ readonly path: string;+ /** Size in bytes. */+ readonly size: number;+}++/** One compiled skill. `listSkillFiles` enumerates its files. */+export interface AgentSkillDescription {+ readonly name: string;+ readonly description: string;+}+/**- * The caller-facing view of an agent: its name, description, and the compiled- * tools `invokeTool` can run, sorted by name. Unlike `GET /eve/v1/info`, it- * carries no paths, config, diagnostics, or other inspection detail, so- * channels can publish it as is. Tools added by dynamic resolvers and- * subagents are not listed.+ * The caller-facing view of an agent: its name, description, the compiled+ * tools `invokeTool` can run, and its compiled skills, each sorted by name.+ * Unlike `GET /eve/v1/info`, it carries no paths, config, diagnostics, or+ * other inspection detail, so channels can publish it as is. Tools and+ * skills added by dynamic resolvers and subagents are not listed.*/export interface AgentDescription {readonly name: string;readonly description?: string;readonly tools: readonly AgentToolDescription[];+ readonly skills: readonly AgentSkillDescription[];+}++/** The `describe`, `listSkillFiles`, and `readSkill` route handler args. */+export interface AgentDescriptionRouteArgs {+ describe(): Promise<AgentDescription>;+ listSkillFiles(skill: string): Promise<readonly AgentSkillFileDescription[]>;+ readSkill(skill: string, path?: string): Promise<Uint8Array>;+}++/**+ * One compiled agent as its routes see it: the description projected from+ * its manifest, and the source of its skill files. Loading it reads the+ * manifest only; no skill file is touched until one is listed or read.+ */+export interface DescribedAgent {+ readonly description: AgentDescription;+ readonly files: SkillFileSource;}/**- * The `describe` route handler arg for one compiled agent. The artifacts- * source resolves on first use, so routes that never call it pay nothing.+ * Loads the agent of a compiled artifacts source once per artifact version+ * on the active runtime session, as `getCompiledRuntimeAgentBundle` does for+ * the execution graph, without resolving that graph. A production build+ * loads once per process; `eve dev` reloads after each recompile. A failed+ * load is retried on the next call rather than cached.+ */+export async function loadDescribedAgent(+ compiledArtifactsSource: RuntimeCompiledArtifactsSource,+): Promise<DescribedAgent> {+ const session = getActiveRuntimeSession();+ const sourceKey = getRuntimeCompiledArtifactsCacheKey(compiledArtifactsSource);+ const version = await resolveRuntimeCompiledArtifactsVersionedCacheKey(compiledArtifactsSource);+ const cached = session.describedAgents.get(sourceKey);+ if (cached?.version === version) return await cached.agent;+ const agent = loadCompiledManifest({ compiledArtifactsSource }).then(+ (manifest): DescribedAgent => ({+ description: describeCompiledAgent(manifest),+ files: createCompiledSkillFileSource({+ compiledArtifactsSource,+ workspaceResourceRoot: manifest.workspaceResourceRoot,+ }),+ }),+ );+ agent.catch(() => {+ if (session.describedAgents.get(sourceKey)?.agent === agent) {+ session.describedAgents.delete(sourceKey);+ }+ });+ session.describedAgents.set(sourceKey, { agent, version });+ return await agent;+}++/**+ * The agent route handler args for one compiled artifacts source, which+ * resolves on first use so routes that never call them pay nothing. Also+ * returns the agent's skill files, so a channel that already holds listed+ * paths reads them without the listing `readSkill` repeats per call.*/export function createAgentDescriptionRouteArgs(resolveCompiledArtifactsSource: () => RuntimeCompiledArtifactsSource,-): { describe(): Promise<AgentDescription> } {+): { readonly args: AgentDescriptionRouteArgs; readonly skillFiles: SkillFileSource } {+ const load = () => loadDescribedAgent(resolveCompiledArtifactsSource());+ const skillFiles: SkillFileSource = {+ listFiles: async (skill) => await (await load()).files.listFiles(skill),+ listDirectories: async (skill) => await (await load()).files.listDirectories(skill),+ readFile: async (skill, path) => await (await load()).files.readFile(skill, path),+ };+ const assertSkill = async (skill: string) => {+ const { description } = await load();+ if (!description.skills.some((entry) => entry.name === skill)) {+ throw new SkillReadError("unknown-skill", `Unknown skill "${skill}".`);+ }+ };return {- async describe() {- const compiledArtifactsSource = resolveCompiledArtifactsSource();- return describeCompiledAgent(await loadCompiledManifest({ compiledArtifactsSource }));+ args: {+ describe: async () => (await load()).description,+ async listSkillFiles(skill) {+ await assertSkill(skill);+ return await skillFiles.listFiles(skill);+ },+ async readSkill(skill, path) {+ await assertSkill(skill);+ return await readSkillFile({ path, skill, source: skillFiles });+ },},+ skillFiles,};}@@ -46,11 +145,15 @@ export function createAgentDescriptionRouteArgs(export function describeCompiledAgent(manifest: CompiledAgentManifest): AgentDescription {const tools = manifest.tools.filter((tool) => isInvocableCompiledTool(manifest, tool))- .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))+ .sort((left, right) => comparePaths(left.name, right.name)).map(describeTool);+ const skills = [...manifest.skills]+ .sort((left, right) => comparePaths(left.name, right.name))+ .map(({ name, description }) => ({ name, description }));const description: { -readonly [K in keyof AgentDescription]: AgentDescription[K] } = {name: manifest.config.name,tools,+ skills,};if (manifest.config.description !== undefined) {description.description = manifest.config.description;diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex 4bc7944ef..ac9c07e80 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -7,7 +7,7 @@ import type { InputResponse } from "#shared/input.js";import type { Session } from "#channel/session.js";import type { JsonObject } from "#shared/json.js";import type { ChannelMethod } from "#public/definitions/channel.js";-import type { AgentDescription } from "#channel/agent-description.js";+import type { AgentDescription, AgentSkillFileDescription } from "#channel/agent-description.js";type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Record<string, string>;@@ -35,11 +35,26 @@ export interface RouteHandlerArgs<TState = undefined> {/** Best-effort client IP reported by the host, or `null` when unavailable. */requestIp: string | null;/**- * Describes the agent for callers: its name, description, and the compiled- * tools that can run outside a turn, sorted by name. Carries none of the- * inspection detail of `GET /eve/v1/info`.+ * Describes the agent for callers: its name, description, the compiled+ * tools that can run outside a turn, and the name and description of each+ * compiled skill, sorted by name. Reads the compiled manifest only, no+ * skill file, and carries none of the inspection detail of `GET /eve/v1/info`.*/describe(): Promise<AgentDescription>;+ /**+ * Lists the regular files of one compiled skill, each with its path under+ * the skill root and its size in bytes, sorted by path. Rejects a skill+ * the agent does not have.+ */+ listSkillFiles(skill: string): Promise<readonly AgentSkillFileDescription[]>;+ /**+ * Reads one file of a compiled skill as raw bytes. `path` is relative to+ * the skill root and defaults to its `SKILL.md`. Rejects paths that are+ * absolute or contain `.`, `..`, or empty segments, files the skill does+ * not list, and files over 512 KiB. Production builds ship skill files as+ * server assets, so they count toward the deployed function's size.+ */+ readSkill(skill: string, path?: string): Promise<Uint8Array>;/** Runs one of the agent's tools as `auth`, outside any conversation. */readonly invokeTool: InvokeToolFn;}diff --git a/packages/eve/src/channel/skill-files.integration.test.ts b/packages/eve/src/channel/skill-files.integration.test.tsnew file mode 100644index 000000000..2ff65e579--- /dev/null+++ b/packages/eve/src/channel/skill-files.integration.test.ts@@ -0,0 +1,87 @@+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterAll, beforeAll, describe, expect, it } from "vitest";++import {+ createDiskSkillFileSource,+ MAX_SKILL_FILE_BYTES,+ type SkillFileSource,+} from "#channel/skill-files.js";++describe("createDiskSkillFileSource", () => {+ let root: string;+ let source: SkillFileSource;++ // `skills/triage` holds regular files beside a symlinked file and a+ // symlinked directory; `skills/linked` is a symlinked skill root; and the+ // source itself is opened through `alias`, a symlink to `skills`, since a+ // real deployment's compile directory can sit behind one (macOS's tmpdir+ // does), so containment must compare real paths.+ beforeAll(async () => {+ root = await mkdtemp(join(tmpdir(), "eve-skill-files-"));+ const skills = join(root, "skills");+ const alias = join(root, "alias");+ const outside = join(root, "outside");+ await mkdir(join(skills, "triage", "references"), { recursive: true });+ await mkdir(join(skills, "triage", "templates", "regional"), { recursive: true });+ await mkdir(outside, { recursive: true });+ await writeFile(join(skills, "triage", "SKILL.md"), "# Triage\n");+ await writeFile(join(skills, "triage", "references", "api.md"), "api\n");+ await writeFile(join(skills, "triage", "big.bin"), new Uint8Array(MAX_SKILL_FILE_BYTES + 1));+ await writeFile(join(outside, "secret.md"), "secret\n");+ await symlink(join(outside, "secret.md"), join(skills, "triage", "leaked.md"));+ await symlink(outside, join(skills, "triage", "escape"));+ await symlink(join(skills, "triage"), join(skills, "linked"));+ await symlink(skills, alias);+ source = createDiskSkillFileSource(alias);+ });++ afterAll(async () => {+ await rm(root, { force: true, recursive: true });+ });++ it("lists only regular files reached through real directories", async () => {+ await expect(source.listFiles("triage")).resolves.toEqual([+ { path: "SKILL.md", size: 9 },+ { path: "big.bin", size: MAX_SKILL_FILE_BYTES + 1 },+ { path: "references/api.md", size: 4 },+ ]);+ await expect(source.listFiles("linked")).resolves.toEqual([]);+ await expect(source.listFiles("missing")).resolves.toEqual([]);+ });++ it("lists every real directory, empty ones included", async () => {+ await expect(source.listDirectories("triage")).resolves.toEqual([+ "references",+ "templates",+ "templates/regional",+ ]);+ await expect(source.listDirectories("linked")).resolves.toEqual([]);+ await expect(source.listDirectories("missing")).resolves.toEqual([]);+ });++ it("reads regular files under the real skill root", async () => {+ await expect(source.readFile("triage", "SKILL.md")).resolves.toEqual(+ new TextEncoder().encode("# Triage\n"),+ );+ await expect(source.readFile("triage", "references/api.md")).resolves.toEqual(+ new TextEncoder().encode("api\n"),+ );+ });++ it.each([+ ["linked", "SKILL.md", "unknown-file"],+ ["missing", "SKILL.md", "unknown-file"],+ ["triage", "missing.md", "unknown-file"],+ ["triage", "references/missing.md", "unknown-file"],+ ["triage", "SKILL.md/below", "unknown-file"],+ ["triage", "references", "unknown-file"],+ ["triage", "leaked.md", "unknown-file"],+ ["triage", "escape/secret.md", "unknown-file"],+ ["triage", "big.bin", "too-large"],+ ])("refuses %s/%s as %s", async (skill, path, code) => {+ await expect(source.readFile(skill, path)).rejects.toMatchObject({ code });+ });+});diff --git a/packages/eve/src/channel/skill-files.test.ts b/packages/eve/src/channel/skill-files.test.tsnew file mode 100644index 000000000..b59433a2f--- /dev/null+++ b/packages/eve/src/channel/skill-files.test.ts@@ -0,0 +1,93 @@+import { createHash } from "node:crypto";++import { describe, expect, it } from "vitest";++import {+ createCompiledSkillFileSource,+ MAX_SKILL_FILE_BYTES,+ readSkillFile,+ skillFileStorageKey,+ SKILL_FILES_INDEX_KEY,+ type SkillFileSource,+} from "#channel/skill-files.js";++const files: Readonly<Record<string, Uint8Array>> = {+ "skill.md": new TextEncoder().encode("# Triage\n"),+ "references/api.md": new Uint8Array([0xe9, 0x00]),+ "big.bin": new Uint8Array(MAX_SKILL_FILE_BYTES + 1),+};+const memory: SkillFileSource = {+ listFiles: async () =>+ Object.entries(files).map(([path, bytes]) => ({ path, size: bytes.byteLength })),+ listDirectories: async () => ["references"],+ readFile: async (_skill, path) => files[path]!,+};++// A production build's index and server assets; `stale.md` ships altered bytes.+const shipped = new Uint8Array([1, 2, 3]);+const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");+const bundled = createCompiledSkillFileSource({+ compiledArtifactsSource: { kind: "bundled" },+ openStorage: async () => ({+ getItemRaw: async (key) =>+ key === SKILL_FILES_INDEX_KEY+ ? JSON.stringify({+ version: 1,+ skills: [+ [+ "triage",+ [+ ["SKILL.md", 3, digest(shipped)],+ ["huge.md", MAX_SKILL_FILE_BYTES + 1, null],+ ["stale.md", 3, digest(new Uint8Array([9, 9, 9]))],+ ],+ ["templates"],+ ],+ ],+ })+ : key === skillFileStorageKey(digest(shipped))+ ? shipped+ : new Uint8Array([7, 7, 7]),+ }),+ workspaceResourceRoot: { logicalPath: "workspace-resources/__root__", rootEntries: [] },+});++describe("bundled skill files", () => {+ it("lists files and directories from the build index", async () => {+ await expect(bundled.listFiles("triage")).resolves.toEqual([+ { path: "SKILL.md", size: 3 },+ { path: "huge.md", size: MAX_SKILL_FILE_BYTES + 1 },+ { path: "stale.md", size: 3 },+ ]);+ await expect(bundled.listDirectories("triage")).resolves.toEqual(["templates"]);+ await expect(bundled.listDirectories("missing")).resolves.toEqual([]);+ });+});++describe("readSkillFile", () => {+ it.each([+ ["../other/SKILL.md", memory, "invalid-path"],+ ["./SKILL.md", memory, "invalid-path"],+ ["/etc/passwd", memory, "invalid-path"],+ ["C:/Windows/win.ini", memory, "invalid-path"],+ ["references\\api.md", memory, "invalid-path"],+ ["references//api.md", memory, "invalid-path"],+ ["SKILL.md\0.png", memory, "invalid-path"],+ ["", memory, "invalid-path"],+ ["references/API.md", memory, "unknown-file"],+ ["big.bin", memory, "too-large"],+ ["huge.md", bundled, "too-large"],+ ["stale.md", bundled, "unavailable"],+ [undefined, memory, files["skill.md"]],+ ["SKILL.md", memory, files["skill.md"]],+ ["references/api.md", memory, files["references/api.md"]],+ [undefined, bundled, shipped],+ ] as const)("reads %j", async (path, source, expected) => {+ const read = readSkillFile({ path, skill: "triage", source });+ if (typeof expected === "string") {+ await expect(read).rejects.toMatchObject({ code: expected });+ } else {+ await expect(read).resolves.toEqual(expected);+ }+ });+});diff --git a/packages/eve/src/channel/skill-files.ts b/packages/eve/src/channel/skill-files.tsnew file mode 100644index 000000000..cb3deef8e--- /dev/null+++ b/packages/eve/src/channel/skill-files.ts@@ -0,0 +1,400 @@+import { createHash } from "node:crypto";+import { constants } from "node:fs";+import { lstat, open, readdir, realpath } from "node:fs/promises";+import nodePath from "node:path";++import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";+import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";++/** Largest skill file `readSkill` returns. */+export const MAX_SKILL_FILE_BYTES = 512 * 1024;++/** Canonical file name of a skill package's entry markdown. */+export const SKILL_ENTRY_FILE_NAME = "SKILL.md";++/**+ * Whether a file name is a skill's entry markdown. Discovery accepts any case+ * variant, such as `skill.md`, and materialization keeps the authored name.+ */+export function isSkillEntryFileName(name: string): boolean {+ return name.toLowerCase() === "skill.md";+}++export type SkillReadErrorCode =+ | "invalid-path"+ | "too-large"+ | "unavailable"+ | "unknown-file"+ | "unknown-skill";++/** Thrown by `readSkill`. `code` lets a channel map the failure onto its own protocol. */+export class SkillReadError extends Error {+ readonly code: SkillReadErrorCode;++ constructor(code: SkillReadErrorCode, message: string) {+ super(message);+ this.name = "SkillReadError";+ this.code = code;+ }+}++/** One regular file of a skill: its `/`-separated path under the skill root and its size. */+export interface SkillFileEntry {+ readonly path: string;+ readonly size: number;+}++/**+ * Lookup into the compiled skill files of one agent. Paths are `/`-separated+ * and relative to the skill root, e.g. `SKILL.md` or `references/api.md`.+ */+export interface SkillFileSource {+ /** Regular files of one skill, sorted by path. Empty when the skill has no materialized files. */+ listFiles(skill: string): Promise<readonly SkillFileEntry[]>;+ /**+ * Every directory of one skill below its root, sorted by path, including+ * empty ones that no listed file implies.+ */+ listDirectories(skill: string): Promise<readonly string[]>;+ readFile(skill: string, path: string): Promise<Uint8Array>;+}++/** Nitro `serverAssets` base that holds the root agent's shipped skill files. */+export const SKILL_FILES_SERVER_ASSET_BASE = "eve-skills";++/** Nitro `serverAssets` base that holds {@link SKILL_FILES_INDEX_KEY}. */+export const SKILL_FILES_INDEX_SERVER_ASSET_BASE = "eve-skill-index";++/** Key of the skill file index inside {@link SKILL_FILES_INDEX_SERVER_ASSET_BASE}. */+export const SKILL_FILES_INDEX_KEY = "skills.json";++/**+ * One indexed file: `[path, size, sha256]`. `sha256` is `null` for files over+ * {@link MAX_SKILL_FILE_BYTES}, which are listed but not shipped. A shipped+ * file's storage key is {@link skillFileStorageKey} of its digest.+ */+export type SkillFilesIndexEntry = readonly [path: string, size: number, sha256: string | null];++/**+ * Index of the skill files a production build ships, written by `eve build`.+ * eve owns the listing rather than deriving it from storage keys, so real+ * paths never pass through unstorage key normalization. Entries are arrays,+ * not object keys, so names such as `__proto__` stay plain data.+ */+export interface SkillFilesIndex {+ readonly version: 1;+ /** `[skill, files, directories]`, sorted by skill then path. */+ readonly skills: readonly (readonly [+ skill: string,+ files: readonly SkillFilesIndexEntry[],+ directories: readonly string[],+ ])[];+}++/**+ * Storage key of a shipped skill file: its SHA-256 with a `.bin` name. `.bin`+ * makes Nitro inline the file as a `Uint8Array` whatever its real extension,+ * and a hex name is left unchanged by unstorage key normalization.+ */+export function skillFileStorageKey(sha256: string): string {+ return `${sha256}.bin`;+}++/** The subset of an unstorage `Storage` the server asset source reads with. */+export interface SkillFileStorage {+ getItemRaw(key: string): Promise<unknown>;+}++/** Opens a Nitro server asset storage, e.g. `useStorage("assets:eve-skills")`. */+export type OpenSkillFileStorage = (base: string) => Promise<SkillFileStorage>;++const openNitroStorage: OpenSkillFileStorage = async (base) => {+ const { useStorage } = await import("nitro/storage");+ return useStorage(`assets:${base}`);+};++/**+ * Selects the skill file source for the active compiled artifacts.+ *+ * Skill files are materialized under the node's workspace resource root by+ * `compiler/workspace-resources.ts`. Disk artifacts (dev) read that tree with+ * {@link createDiskSkillFileSource}; bundled artifacts (production builds)+ * read the Nitro server assets `eve build` registers for the root agent.+ */+export function createCompiledSkillFileSource(input: {+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;+ readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;+ readonly openStorage?: OpenSkillFileStorage;+}): SkillFileSource {+ if (input.compiledArtifactsSource.kind !== "disk") {+ return createServerAssetSkillFileSource(input.openStorage ?? openNitroStorage);+ }+ const { compileDirectoryPath } = resolveRuntimeCompilerArtifactPaths(+ input.compiledArtifactsSource.appRoot,+ );+ return createDiskSkillFileSource(+ `${compileDirectoryPath}/${input.workspaceResourceRoot.logicalPath}/skills`,+ );+}++/**+ * Reads skill files from the Nitro server assets of a production build.+ * Listing and sizes come from the eve index, so an over-limit file is+ * rejected without loading it. The bytes storage returns must match the+ * indexed size and SHA-256; anything else is `unavailable` rather than+ * served altered.+ */+function createServerAssetSkillFileSource(openStorage: OpenSkillFileStorage): SkillFileSource {+ let index: Promise<Map<string, IndexedSkill>> | undefined;+ const loadIndex = () => {+ index ??= openStorage(SKILL_FILES_INDEX_SERVER_ASSET_BASE)+ .then((storage) => storage.getItemRaw(SKILL_FILES_INDEX_KEY))+ .then(parseSkillFilesIndex);+ // A failed load is retried on the next call rather than cached.+ index.catch(() => {+ index = undefined;+ });+ return index;+ };+ return {+ async listFiles(skill) {+ return ((await loadIndex()).get(skill)?.files ?? []).map(([path, size]) => ({ path, size }));+ },+ async listDirectories(skill) {+ return (await loadIndex()).get(skill)?.directories ?? [];+ },+ async readFile(skill, path) {+ const entry = (await loadIndex()).get(skill)?.files.find(([indexed]) => indexed === path);+ if (entry === undefined) throw unknownFile(skill, path);+ const [, size, sha256] = entry;+ if (sha256 === null) throw tooLarge(skill, path, size);+ const storage = await openStorage(SKILL_FILES_SERVER_ASSET_BASE);+ const bytes = await storage.getItemRaw(skillFileStorageKey(sha256));+ if (+ !(bytes instanceof Uint8Array) ||+ bytes.byteLength !== size ||+ createHash("sha256").update(bytes).digest("hex") !== sha256+ ) {+ throw new SkillReadError(+ "unavailable",+ `Skill "${skill}" file "${path}" does not match its build index; this build did not ship it byte for byte.`,+ );+ }+ return bytes;+ },+ };+}++interface IndexedSkill {+ readonly files: readonly SkillFilesIndexEntry[];+ readonly directories: readonly string[];+}++function parseSkillFilesIndex(raw: unknown): Map<string, IndexedSkill> {+ const text =+ typeof raw === "string" ? raw : raw instanceof Uint8Array ? new TextDecoder().decode(raw) : "";+ let parsed: unknown;+ try {+ parsed = text === "" ? undefined : JSON.parse(text);+ } catch {+ parsed = undefined;+ }+ if (!isSkillFilesIndex(parsed)) {+ throw new SkillReadError(+ "unavailable",+ "Skill files are not available: this server was not built by `eve build`, so it carries no skill files.",+ );+ }+ return new Map(+ parsed.skills.map(([skill, files, directories]) => [skill, { directories, files }]),+ );+}++function isSkillFilesIndex(value: unknown): value is SkillFilesIndex {+ if (typeof value !== "object" || value === null) return false;+ const { skills, version } = value as { skills?: unknown; version?: unknown };+ return (+ version === 1 &&+ Array.isArray(skills) &&+ skills.every(+ (entry) =>+ Array.isArray(entry) &&+ typeof entry[0] === "string" &&+ Array.isArray(entry[1]) &&+ entry[1].every(+ (file: unknown) =>+ Array.isArray(file) &&+ file.length === 3 &&+ typeof file[0] === "string" &&+ Number.isSafeInteger(file[1]) &&+ (typeof file[2] === "string" || file[2] === null),+ ) &&+ Array.isArray(entry[2]) &&+ entry[2].every((directory: unknown) => typeof directory === "string"),+ )+ );+}++/**+ * Reads skill files from a materialized `skills/<name>/` tree.+ *+ * Only regular files reached through real directories are served: a+ * symlinked skill root lists nothing, listing skips symlinks, every path+ * component is checked with `lstat` before opening, the leaf is opened with+ * `O_NOFOLLOW` where the platform defines it, and the `realpath` of the+ * target must stay under the `realpath` of the skill root. These checks are+ * not atomic; the tree is the app's own compile output, so a writer that+ * could race them can already change what is served.+ */+export function createDiskSkillFileSource(skillsRoot: string): SkillFileSource {+ return {+ async listFiles(skill) {+ const skillRoot = `${skillsRoot}/${skill}`;+ if (!(await isRealDirectory(skillRoot))) return [];+ const { files } = await walkSkill(skillRoot);+ return files.sort((left, right) => comparePaths(left.path, right.path));+ },+ async listDirectories(skill) {+ const skillRoot = `${skillsRoot}/${skill}`;+ if (!(await isRealDirectory(skillRoot))) return [];+ const { directories } = await walkSkill(skillRoot);+ return directories.sort(comparePaths);+ },+ async readFile(skill, path) {+ const skillRoot = `${skillsRoot}/${skill}`;+ if (!(await isRealDirectory(skillRoot))) throw unknownFile(skill, path);+ const segments = path.split("/");+ let current = skillRoot;+ for (const [index, segment] of segments.entries()) {+ current = `${current}/${segment}`;+ const stats = await lstatOrUndefined(current);+ const isLeaf = index === segments.length - 1;+ if (stats === undefined || (isLeaf ? !stats.isFile() : !stats.isDirectory())) {+ throw unknownFile(skill, path);+ }+ }+ const [realRoot, realTarget] = await Promise.all([realpath(skillRoot), realpath(current)]);+ const relative = nodePath.relative(realRoot, realTarget);+ if (+ relative === "" ||+ nodePath.isAbsolute(relative) ||+ relative.split(nodePath.sep)[0] === ".."+ ) {+ throw unknownFile(skill, path);+ }+ const handle = await open(current, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const stats = await handle.stat();+ if (!stats.isFile()) throw unknownFile(skill, path);+ if (stats.size > MAX_SKILL_FILE_BYTES) throw tooLarge(skill, path, stats.size);+ return new Uint8Array(await handle.readFile());+ } finally {+ await handle.close();+ }+ },+ };+}++async function lstatOrUndefined(path: string) {+ try {+ return await lstat(path);+ } catch (error) {+ if (+ error instanceof Error &&+ "code" in error &&+ (error.code === "ENOENT" || error.code === "ENOTDIR")+ ) {+ return undefined;+ }+ throw error;+ }+}++async function isRealDirectory(path: string): Promise<boolean> {+ return (await lstatOrUndefined(path))?.isDirectory() === true;+}++/** The regular files and real directories below a skill root, unsorted. */+async function walkSkill(+ skillRoot: string,+): Promise<{ files: SkillFileEntry[]; directories: string[] }> {+ const files: SkillFileEntry[] = [];+ const directories: string[] = [];+ const walk = async (directory: string, prefix: string) => {+ for (const entry of await readdir(directory, { withFileTypes: true })) {+ const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;+ // Dirent reports symlinks as neither files nor directories, so they are skipped.+ if (entry.isDirectory()) {+ directories.push(path);+ await walk(`${directory}/${entry.name}`, path);+ } else if (entry.isFile()) {+ const stats = await lstatOrUndefined(`${directory}/${entry.name}`);+ if (stats?.isFile() === true) files.push({ path, size: stats.size });+ }+ }+ };+ await walk(skillRoot, "");+ return { directories, files };+}++function unknownFile(skill: string, path: string): SkillReadError {+ return new SkillReadError("unknown-file", `Skill "${skill}" has no file "${path}".`);+}++function tooLarge(skill: string, path: string, size: number): SkillReadError {+ return new SkillReadError(+ "too-large",+ `Skill "${skill}" file "${path}" is ${size} bytes, over the ${MAX_SKILL_FILE_BYTES}-byte limit.`,+ );+}++/**+ * Reads one file of one skill, byte for byte, given any caller-supplied path.+ *+ * With no `path`, reads the skill's entry markdown under whatever case variant+ * of `SKILL.md` it was authored with. An explicit top-level `SKILL.md` matches+ * the entry file case-insensitively too; every other path must match a listed+ * file exactly. Files over {@link MAX_SKILL_FILE_BYTES} are `too-large`.+ */+export async function readSkillFile(input: {+ readonly path?: string;+ readonly skill: string;+ readonly source: SkillFileSource;+}): Promise<Uint8Array> {+ const requested = input.path ?? SKILL_ENTRY_FILE_NAME;+ assertRelativeSkillPath(requested);+ const files = await input.source.listFiles(input.skill);+ const file =+ files.find((entry) => entry.path === requested) ??+ (isSkillEntryFileName(requested)+ ? files.find((entry) => isSkillEntryFileName(entry.path))+ : undefined);+ if (file === undefined) throw unknownFile(input.skill, requested);+ if (file.size > MAX_SKILL_FILE_BYTES) throw tooLarge(input.skill, file.path, file.size);+ const bytes = await input.source.readFile(input.skill, file.path);+ // The file can change between the listing and the read.+ if (bytes.byteLength > MAX_SKILL_FILE_BYTES) {+ throw tooLarge(input.skill, file.path, bytes.byteLength);+ }+ return bytes;+}++function assertRelativeSkillPath(path: string): void {+ const invalid = (reason: string) =>+ new SkillReadError("invalid-path", `Skill file path "${path}" ${reason}.`);+ if (path.length === 0) throw invalid("must not be empty");+ if (path.startsWith("/") || /^[A-Za-z]:/.test(path)) {+ throw invalid("must be relative to the skill root");+ }+ if (path.includes("\\") || path.includes("\0")) {+ throw invalid('must use "/" separators and contain no NUL bytes');+ }+ if (path.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {+ throw invalid('must not contain empty, ".", or ".." segments');+ }+}++export function comparePaths(left: string, right: string): number {+ return left < right ? -1 : left > right ? 1 : 0;+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 6726adcbc..575cdd94a 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -127,10 +127,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},channel: {- current: 49,+ current: 50,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,- 43, 44, 45, 46, 47, 48, 49,+ 43, 44, 45, 46, 47, 48, 49, 50,],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",diff --git a/packages/eve/src/internal/mcp/skills.test.ts b/packages/eve/src/internal/mcp/skills.test.tsnew file mode 100644index 000000000..fd3486837--- /dev/null+++ b/packages/eve/src/internal/mcp/skills.test.ts@@ -0,0 +1,383 @@+import { describe, expect, it } from "vitest";++import {+ MAX_SKILL_FILE_BYTES,+ type SkillFileSource,+ SkillReadError,+} from "#channel/skill-files.js";+import { createMcpSkillsFeature, type McpSkillSource } from "#internal/mcp/skills.js";+import { createMcpStreamableHttpServer } from "#internal/mcp/streamable-http-server.js";++/**+ * A skill's files; `null` is listed but missing on read (a deterministic+ * `SkillReadError`), a function is called per read so a test can fail+ * transiently, and a path ending in `/` is an empty directory.+ */+type Files = Readonly<Record<string, string | Uint8Array | null | (() => string)>>;++const PROTOCOL = "2026-07-28";+const encode = (content: string | Uint8Array) =>+ typeof content === "string" ? new TextEncoder().encode(content) : content;++/**+ * A skill source as the route args provide one: the `skills` array is+ * stable for the life of the source, as a build's description is, and+ * `calls` counts listings and reads per skill.+ */+function skillSource(skills: Readonly<Record<string, Files>>) {+ const calls = { list: new Map<string, number>(), read: new Map<string, number>() };+ const count = (calls: Map<string, number>, key: string) =>+ calls.set(key, (calls.get(key) ?? 0) + 1);+ const files: SkillFileSource = {+ async listFiles(skill) {+ count(calls.list, skill);+ return Object.entries(skills[skill] ?? {})+ .filter(([path]) => !path.endsWith("/"))+ .map(([path, content]) => ({+ path,+ size: content === null || typeof content === "function" ? 1 : encode(content).length,+ }))+ .sort((left, right) => (left.path < right.path ? -1 : 1));+ },+ async listDirectories(skill) {+ const directories = new Set<string>();+ for (const path of Object.keys(skills[skill] ?? {})) {+ const segments = path.split("/").filter(Boolean);+ const depth = path.endsWith("/") ? segments.length : segments.length - 1;+ for (let index = 1; index <= depth; index += 1) {+ directories.add(segments.slice(0, index).join("/"));+ }+ }+ return [...directories].sort();+ },+ async readFile(skill, path) {+ count(calls.read, `${skill}/${path}`);+ const content = skills[skill]?.[path];+ if (content === undefined || content === null) {+ throw new SkillReadError("unknown-file", `Skill "${skill}" has no file "${path}".`);+ }+ return encode(typeof content === "function" ? content() : content);+ },+ };+ const source: McpSkillSource = {+ files,+ skills: Object.keys(skills).map((name) => ({ name, description: "Catalog description." })),+ };+ return { calls, source };+}++/** Every request builds a fresh server, as `mcpChannel` does. */+function handler(skills: Readonly<Record<string, Files>>, source = skillSource(skills).source) {+ return async (method: string, params: Record<string, unknown> = {}) => {+ const mcp = createMcpStreamableHttpServer({+ authenticate: async () => null,+ features: [createMcpSkillsFeature(source)],+ name: "eve-skills-test",+ version: "0.0.0",+ });+ const _meta = {+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": { name: "skills-test", version: "0.0.0" },+ "io.modelcontextprotocol/protocolVersion": PROTOCOL,+ };+ const request = new Request("https://agent.example/eve/v1/mcp", {+ body: JSON.stringify({ id: 1, jsonrpc: "2.0", method, params: { ...params, _meta } }),+ headers: {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ "mcp-method": method,+ "mcp-protocol-version": PROTOCOL,+ ...(method === "resources/read" && { "mcp-name": String(params.uri) }),+ },+ method: "POST",+ });+ return (await (await mcp(request)).json()) as { result?: Record<string, any>; error?: object };+ };+}++/** Whether each surface serves a skill: skills/list, resources/list, get, read, directory. */+async function surfaces(call: ReturnType<typeof handler>, names: readonly string[]) {+ const listed = (await call("skills/list")).result?.skills.map((s: { uri: string }) => s.uri);+ const resources = (await call("resources/list")).result?.resources.map(+ (r: { uri: string }) => r.uri,+ );+ const served: Record<string, boolean[]> = {};+ for (const name of names) {+ const root = `skill://${encodeURIComponent(name)}`;+ const entry = `${root}/SKILL.md`;+ served[name] = [+ listed.includes(entry),+ resources.includes(entry),+ (await call("skills/get", { uri: entry })).result !== undefined,+ (await call("resources/read", { uri: entry })).result !== undefined,+ (await call("resources/read", { uri: `${root}/notes.md` })).result !== undefined,+ (await call("resources/directory/read", { uri: root })).result !== undefined,+ ];+ }+ return served;+}++const doc = (name: string, description: string) => ({+ "SKILL.md": `---\nname: ${JSON.stringify(name)}\ndescription: ${JSON.stringify(description)}\n---\nBody\n`,+ "notes.md": "notes\n",+});+const max = "a".repeat(64);+const every = Array(6).fill(true);+const none = Array(6).fill(false);+const bulky: Record<string, string> = doc("bulky", "Too much.");+for (let index = 0; index < 33; index += 1) {+ bulky[`data/part-${index}.txt`] = "z".repeat(MAX_SKILL_FILE_BYTES);+}+const crowded: Record<string, string> = doc("crowded", "Too many files.");+for (let index = 0; index < 511; index += 1) crowded[`data/${index}.txt`] = "";++describe("MCP skills (SEP-2640)", () => {+ it("serves a skill whole on every surface or not at all", async () => {+ // Without frontmatter, eve writes name and description from the catalog.+ const served: Record<string, Files> = {+ a: doc("a", "x"),+ [max]: doc(max, "d".repeat(1024)),+ "multi-byte": doc("multi-byte", "é".repeat(1024)),+ synthesized: { "SKILL.md": "Body\n", "notes.md": "notes\n" },+ "lower-entry": { "skill.md": "Body\n", "notes.md": "notes\n" },+ };+ const refused: Record<string, Files> = {+ Hello_World: doc("Hello_World", "Underscore."),+ [`${max}a`]: doc(`${max}a`, "Name too long."),+ "double--hyphen": doc("double--hyphen", "Consecutive hyphens."),+ "blank-desc": doc("blank-desc", " "),+ "long-desc": doc("long-desc", "d".repeat(1025)),+ broken: { "SKILL.md": "---\nname: broken\ndescription: [unclosed\n---\n", "notes.md": "n" },+ binary: { "SKILL.md": new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00]), "notes.md": "n" },+ "no-entry": { "notes.md": "n" },+ "two-entries": { ...doc("two-entries", "Twice."), "skill.md": "Again\n" },+ "over-cap-file": {+ ...doc("over-cap-file", "Big."),+ "big.md": "x".repeat(MAX_SKILL_FILE_BYTES + 1),+ },+ unreadable: { ...doc("unreadable", "Gone."), "gone.md": null },+ bulky,+ crowded,+ };+ const call = handler({ ...served, ...refused });+ const result = await surfaces(call, [...Object.keys(served), ...Object.keys(refused)]);+ for (const name of Object.keys(served)) expect(result[name], name).toEqual(every);+ for (const name of Object.keys(refused)) expect(result[name], name).toEqual(none);++ const get = await call("skills/get", { uri: "skill://synthesized/SKILL.md" });+ const synthesized =+ '---\nname: "synthesized"\ndescription: "Catalog description."\n---\nBody\n';+ expect(get.result?.skill).toEqual({+ uri: "skill://synthesized/SKILL.md",+ frontmatter: { name: "synthesized", description: "Catalog description." },+ resources: [+ {+ uri: "skill://synthesized/SKILL.md",+ digest: `sha256:${await sha256(synthesized)}`,+ size: synthesized.length,+ },+ {+ uri: "skill://synthesized/notes.md",+ digest: `sha256:${await sha256("notes\n")}`,+ size: 6,+ },+ ],+ });+ const read = await call("resources/read", { uri: "skill://synthesized/SKILL.md" });+ expect(read.result?.contents).toEqual([+ { uri: "skill://synthesized/SKILL.md", mimeType: "text/markdown", text: synthesized },+ ]);+ });+});++describe("MCP skills catalog", () => {+ it("advertises resources without list-changed notifications", async () => {+ const call = handler({ hinted: doc("hinted", "Cached.") });+ const { result } = await call("server/discover");+ expect(result?.capabilities).toEqual({+ extensions: { "io.modelcontextprotocol/skills": { directoryRead: true } },+ resources: { listChanged: false },+ });+ });++ it("lists and reads each skill once while its description is stable", async () => {+ const skills = { a: doc("a", "First."), b: doc("b", "Second.") };+ const { calls, source } = skillSource(skills);+ const call = handler(skills, source);+ for (let request = 0; request < 3; request += 1) {+ expect((await call("skills/list")).result?.skills).toHaveLength(2);+ expect((await call("resources/list")).result?.resources).toHaveLength(2);+ expect((await call("skills/get", { uri: "skill://a/SKILL.md" })).result).toBeDefined();+ expect((await call("resources/read", { uri: "skill://b/SKILL.md" })).result).toBeDefined();+ }+ expect([...calls.list]).toEqual([+ ["a", 1],+ ["b", 1],+ ]);+ expect([...calls.read]).toEqual([+ ["a/SKILL.md", 1],+ ["a/notes.md", 1],+ ["b/SKILL.md", 1],+ ["b/notes.md", 1],+ ]);++ // Only `SKILL.md` stays in memory; other files are read per request.+ expect((await call("resources/read", { uri: "skill://a/notes.md" })).result).toBeDefined();+ expect(calls.read.get("a/notes.md")).toBe(2);++ // A new description, as after a recompile, lists and reads again.+ const recompiled = skillSource(skills);+ expect((await handler(skills, recompiled.source)("skills/list")).result?.skills).toHaveLength(+ 2,+ );+ expect([...recompiled.calls.list]).toEqual([+ ["a", 1],+ ["b", 1],+ ]);+ });++ it("retries a skill whose file read failed transiently", async () => {+ let reads = 0;+ const skills = {+ flaky: {+ ...doc("flaky", "Reads once it settles."),+ "notes.md": () => {+ reads += 1;+ if (reads === 1) throw new Error("EIO: transient");+ return "notes\n";+ },+ },+ };+ const { calls, source } = skillSource(skills);+ const call = handler(skills, source);+ const first = await call("skills/list");+ expect(first.error).toBeDefined();+ expect(first.result).toBeUndefined();++ const second = await call("skills/list");+ expect(second.result?.skills.map((s: { uri: string }) => s.uri)).toEqual([+ "skill://flaky/SKILL.md",+ ]);+ expect(reads).toBe(2);+ expect(calls.list.get("flaky")).toBe(2);+ });++ it("retries a skill whose listing failed transiently", async () => {+ const skills = { listed: doc("listed", "Lists once it settles.") };+ const { source } = skillSource(skills);+ let listings = 0;+ const call = handler(skills, {+ ...source,+ files: {+ ...source.files,+ async listFiles(skill) {+ listings += 1;+ if (listings === 1) throw new Error("EIO: transient");+ return await source.files.listFiles(skill);+ },+ },+ });+ expect((await call("skills/list")).error).toBeDefined();+ expect((await call("skills/list")).result?.skills).toHaveLength(1);+ expect(listings).toBe(2);+ });++ it("carries the list cache hint on every skill and resource method", async () => {+ const call = handler({ hinted: doc("hinted", "Cached.") });+ const hint = { cacheScope: "private", ttlMs: 5 * 60 * 1000 };+ for (const [method, params] of [+ ["skills/list", {}],+ ["skills/get", { uri: "skill://hinted/SKILL.md" }],+ ["resources/list", {}],+ ["resources/templates/list", {}],+ ["resources/read", { uri: "skill://hinted/notes.md" }],+ ["resources/directory/read", { uri: "skill://hinted" }],+ ] as const) {+ const { result } = await call(method, params);+ expect(result, method).toMatchObject(hint);+ }+ });++ it("reports a file removed after listing as an unknown resource", async () => {+ let gone = false;+ let failing = false;+ const call = handler({+ moved: {+ ...doc("moved", "Loses a file."),+ "notes.md": () => {+ if (gone)+ throw new SkillReadError("unknown-file", 'Skill "moved" has no file "notes.md".');+ if (failing) throw new Error("EIO: storage failure");+ return "notes\n";+ },+ },+ });+ expect((await call("skills/list")).result?.skills).toHaveLength(1);++ gone = true;+ expect((await call("resources/read", { uri: "skill://moved/notes.md" })).error).toMatchObject({+ code: -32602,+ });+ gone = false;+ failing = true;+ expect((await call("resources/read", { uri: "skill://moved/notes.md" })).error).toMatchObject({+ code: -32603,+ });+ });++ it("lists every directory, empty ones included", async () => {+ const call = handler({+ tree: {+ ...doc("tree", "Has empty directories."),+ "templates/": "",+ "scripts/run.sh": "echo\n",+ "scripts/nested/": "",+ },+ });+ const list = async (uri: string) => await call("resources/directory/read", { uri });+ expect((await list("skill://tree")).result?.resources).toEqual([+ { uri: "skill://tree/SKILL.md", name: "SKILL.md", mimeType: "text/markdown" },+ { uri: "skill://tree/notes.md", name: "notes.md", mimeType: "text/markdown" },+ { uri: "skill://tree/scripts", name: "scripts", mimeType: "inode/directory" },+ { uri: "skill://tree/templates", name: "templates", mimeType: "inode/directory" },+ ]);+ expect((await list("skill://tree/scripts")).result?.resources).toEqual([+ { uri: "skill://tree/scripts/nested", name: "nested", mimeType: "inode/directory" },+ { uri: "skill://tree/scripts/run.sh", name: "run.sh", mimeType: "text/x-shellscript" },+ ]);+ expect((await list("skill://tree/templates")).result?.resources).toEqual([]);+ expect((await list("skill://tree/scripts/nested")).result?.resources).toEqual([]);+ for (const uri of [+ "skill://tree/missing",+ "skill://tree/notes.md",+ "skill://tree/templates/x",+ ]) {+ expect((await list(uri)).error, uri).toMatchObject({ code: -32602 });+ }+ });++ it("does not resolve MIME types from Object.prototype", async () => {+ const call = handler({+ proto: {+ ...doc("proto", "Prototype-named files."),+ "notes.constructor": "text\n",+ "x.__proto__": new Uint8Array([0, 1, 2]),+ "y.hasOwnProperty": "text\n",+ },+ });+ const read = async (path: string) =>+ (await call("resources/read", { uri: `skill://proto/${path}` })).result?.contents[0];+ expect(await read("notes.constructor")).toEqual({+ uri: "skill://proto/notes.constructor",+ mimeType: "text/plain",+ text: "text\n",+ });+ expect((await read("x.__proto__"))?.mimeType).toBe("application/octet-stream");+ expect((await read("y.hasOwnProperty"))?.mimeType).toBe("text/plain");+ });+});++async function sha256(text: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));+ return Buffer.from(digest).toString("hex");+}diff --git a/packages/eve/src/internal/mcp/skills.ts b/packages/eve/src/internal/mcp/skills.tsnew file mode 100644index 000000000..fd6b85bcc--- /dev/null+++ b/packages/eve/src/internal/mcp/skills.ts@@ -0,0 +1,628 @@+import { Buffer } from "node:buffer";+import { createHash } from "node:crypto";++import type { AgentSkillDescription } from "#channel/agent-description.js";+import {+ comparePaths,+ isSkillEntryFileName,+ MAX_SKILL_FILE_BYTES,+ SKILL_ENTRY_FILE_NAME,+ type SkillFileEntry,+ type SkillFileSource,+ SkillReadError,+} from "#channel/skill-files.js";+import {+ type McpServer,+ ProtocolError,+ ProtocolErrorCode,+ ResourceNotFoundError,+} from "#compiled/@modelcontextprotocol/server/index.js";+import { z } from "#compiled/zod/index.js";+import { parseFrontmatter } from "#internal/helpers/frontmatter.js";+import { createLogger } from "#internal/logging.js";+import {+ MCP_LIST_CACHE_HINT,+ type McpServerFeature,+} from "#internal/mcp/streamable-http-server.js";+import type { JsonObject } from "#shared/json.js";++/** SEP-2640 extension identifier. */+export const MCP_SKILLS_EXTENSION = "io.modelcontextprotocol/skills";++/** SEP-2640 limits a conforming host must accept; skills over them are not served. */+export const MCP_SKILL_MAX_RESOURCES = 512;+export const MCP_SKILL_MAX_TOTAL_BYTES = 16 * 1024 * 1024;++const SKILL_URI_PREFIX = "skill://";+const DIRECTORY_MIME_TYPE = "inode/directory";+/** Files read concurrently while building one skill entry. */+const READ_CONCURRENCY = 8;++const log = createLogger("mcp.skills");+const warned = new Set<string>();++/** Logs why a skill is not served, once per process. */+function warnOnce(message: string): void {+ if (warned.has(message)) return;+ warned.add(message);+ log.warn(message);+}++/** The skills the feature serves and where their files are. */+export interface McpSkillSource {+ /** The agent's skills as `describe()` lists them. */+ readonly skills: readonly AgentSkillDescription[];+ readonly files: SkillFileSource;+}++/** One `skills/list` entry. */+interface McpSkillEntry {+ readonly uri: string;+ readonly frontmatter: JsonObject;+ readonly resources: readonly {+ readonly uri: string;+ readonly digest: string;+ readonly size: number;+ }[];+}++/**+ * An MCP server feature publishing an agent's compiled skills per SEP-2640:+ * `skills/list`, `skills/get`, `resources/list`, `resources/templates/list`,+ * `resources/read`, and `resources/directory/read`, all under `skill://`.+ *+ * The feature owns the server's resource methods. They are set on the+ * low-level server rather than through `McpServer.registerResource`, whose+ * `resources/read` normalizes the URI with `new URL()` (which resolves `..`)+ * before matching.+ *+ * A skill is served whole or not at all, and an unserved skill is absent+ * from every method. It is served when:+ *+ * - its name and every file path are valid `skill://` segments, and exactly+ * one top-level file is its entry (`SKILL.md` in any case, served as+ * `SKILL.md`);+ * - it has at most 512 files, none over the 512 KiB skill file cap, and at+ * most 16 MiB in total;+ * - every file reads, and the served `SKILL.md` frontmatter meets the Agent+ * Skills format (name rules, description of 1-1024 characters).+ *+ * `SKILL.md` frontmatter that already carries the skill's `name` and a+ * `description` is served byte for byte. Otherwise (flat and module skills,+ * whose materialized `SKILL.md` has no frontmatter, or a package whose `name`+ * differs from its directory) the served document carries rewritten+ * frontmatter, and `frontmatter` and the digest describe that document.+ *+ * Snapshots are keyed by the `skills` array, which `describe()` keeps for+ * as long as the compiled artifacts stay the same, so a skill's files are+ * listed and read once per build: once per process in production, once per+ * recompile under `eve dev`.+ */+export function createMcpSkillsFeature(source: McpSkillSource): McpServerFeature {+ return {+ capabilities: {+ // eve never sends `notifications/resources/list_changed`; the SDK+ // would advertise it for a bare `{}`.+ resources: { listChanged: false },+ extensions: { [MCP_SKILLS_EXTENSION]: { directoryRead: true } },+ },+ register(server) {+ registerSkillHandlers(server, source.files, createSkillCatalog(source));+ },+ };+}++interface SnapshotFile {+ readonly mimeType: string;+ readonly size: number;+}++interface SkillSnapshot {+ readonly name: string;+ readonly description: string;+ readonly entry: McpSkillEntry;+ /** The served `SKILL.md`, which can differ from the authored one. */+ readonly document: ServedFile;+ /** Served files by path, sorted by path. */+ readonly files: ReadonlyMap<string, SnapshotFile>;+ /** Every directory below the skill root, empty ones included. */+ readonly directories: ReadonlySet<string>;+}++interface SkillCatalog {+ served(): Promise<SkillSnapshot[]>;+ skill(name: string): Promise<SkillSnapshot | undefined>;+}++const snapshotCache = new WeakMap<+ readonly AgentSkillDescription[],+ Map<string, Promise<SkillSnapshot | undefined>>+>();++function createSkillCatalog({ files, skills }: McpSkillSource): SkillCatalog {+ const snapshots =+ snapshotCache.get(skills) ?? new Map<string, Promise<SkillSnapshot | undefined>>();+ snapshotCache.set(skills, snapshots);+ const snapshot = async (name: string) => {+ const skill = skills.find((entry) => entry.name === name);+ if (skill === undefined) return undefined;+ let pending = snapshots.get(name);+ if (pending === undefined) {+ pending = snapshotSkill(files, skill);+ snapshots.set(name, pending);+ // A thrown listing or read is retried on the next request rather than cached.+ pending.catch(() => snapshots.delete(name));+ }+ return await pending;+ };+ return {+ async served() {+ const names = skills.map((skill) => skill.name).sort(comparePaths);+ const result: SkillSnapshot[] = [];+ for (const name of names) {+ const built = await snapshot(name);+ if (built !== undefined) result.push(built);+ }+ return result;+ },+ skill: snapshot,+ };+}++function registerSkillHandlers(+ server: McpServer,+ files: SkillFileSource,+ catalog: SkillCatalog,+): void {+ const low = server.server;++ low.setRequestHandler(+ "skills/list",+ { params: z.looseObject({ cursor: z.string().optional() }) },+ async (params) => {+ rejectCursor(params.cursor);+ const skills = (await catalog.served()).map((snapshot) => snapshot.entry);+ return { skills, ...MCP_LIST_CACHE_HINT };+ },+ );++ low.setRequestHandler(+ "skills/get",+ { params: z.looseObject({ uri: z.string() }) },+ async (params) => {+ const parsed = parseSkillUri(params.uri);+ const snapshot =+ parsed?.path === SKILL_ENTRY_FILE_NAME ? await catalog.skill(parsed.skill) : undefined;+ if (snapshot === undefined) {+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown skill: ${params.uri}`, {+ uri: params.uri,+ });+ }+ return { skill: snapshot.entry, ...MCP_LIST_CACHE_HINT };+ },+ );++ low.setRequestHandler(+ "resources/directory/read",+ { params: z.looseObject({ uri: z.string(), cursor: z.string().optional() }) },+ async (params) => {+ rejectCursor(params.cursor);+ const parsed = parseSkillUri(params.uri);+ const snapshot = parsed === undefined ? undefined : await catalog.skill(parsed.skill);+ const resources = snapshot === undefined ? undefined : listDirectory(snapshot, parsed?.path);+ if (resources === undefined) throw new ResourceNotFoundError(params.uri);+ return { resources, ...MCP_LIST_CACHE_HINT };+ },+ );++ low.setRequestHandler("resources/list", async (request) => {+ rejectCursor(request.params?.cursor);+ const resources = (await catalog.served()).map((snapshot) => ({+ uri: snapshot.entry.uri,+ name: snapshot.name,+ description: snapshot.description,+ mimeType: mimeTypeFor(SKILL_ENTRY_FILE_NAME),+ size: snapshot.document.bytes.byteLength,+ }));+ return { resources };+ });++ low.setRequestHandler("resources/templates/list", async (request) => {+ rejectCursor(request.params?.cursor);+ return { resourceTemplates: [] };+ });++ low.setRequestHandler("resources/read", async (request) => {+ const uri = request.params?.uri;+ if (typeof uri !== "string") {+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "params.uri must be a string.");+ }+ const parsed = parseSkillUri(uri);+ const snapshot = parsed?.path === undefined ? undefined : await catalog.skill(parsed.skill);+ const file = parsed?.path === undefined ? undefined : snapshot?.files.get(parsed.path);+ if (snapshot === undefined || parsed?.path === undefined || file === undefined) {+ throw new ResourceNotFoundError(uri);+ }+ // Only `SKILL.md` is held in memory; other files are read again, so a+ // cached snapshot costs its metadata, not every file's bytes.+ const served =+ parsed.path === SKILL_ENTRY_FILE_NAME+ ? snapshot.document+ : toServedFile(await readListedFile(files, snapshot.name, parsed.path, uri));+ const contents =+ served.text === undefined+ ? { uri, mimeType: file.mimeType, blob: Buffer.from(served.bytes).toString("base64") }+ : { uri, mimeType: file.mimeType, text: served.text };+ return { contents: [contents] };+ });+}++/**+ * Reads a file the snapshot listed. One removed since then is an unknown+ * resource; any other failure stays an internal error.+ */+async function readListedFile(+ files: SkillFileSource,+ skill: string,+ path: string,+ uri: string,+): Promise<Uint8Array> {+ try {+ return await files.readFile(skill, path);+ } catch (error) {+ if (error instanceof SkillReadError && error.code === "unknown-file") {+ throw new ResourceNotFoundError(uri);+ }+ throw error;+ }+}++// ---------- Snapshots ----------++interface ServedFile {+ readonly bytes: Uint8Array;+ /** Set when the file is UTF-8 text without NUL bytes. */+ readonly text?: string;+}++function toServedFile(bytes: Uint8Array): ServedFile {+ const text = decodeText(bytes);+ return text === undefined ? { bytes } : { bytes, text };+}++/** Decodes UTF-8 text without NUL bytes; returns `undefined` for anything else. */+function decodeText(bytes: Uint8Array): string | undefined {+ if (bytes.includes(0)) return undefined;+ try {+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);+ } catch {+ return undefined;+ }+}++/**+ * The authored paths of a skill keyed by served path, or why it is not+ * served. Decided from the listing alone, before any file is read.+ */+function servedPaths(+ skill: string,+ files: readonly SkillFileEntry[],+ directories: readonly string[],+): Map<string, string> | string {+ if (!isSafeSegment(skill)) return "its name is not a valid skill:// segment";+ const unsafe = directories.find((path) => !path.split("/").every(isSafeSegment));+ if (unsafe !== undefined) return `its directory "${unsafe}" is not a valid skill:// path`;+ if (files.length > MCP_SKILL_MAX_RESOURCES) {+ return `it has more than ${MCP_SKILL_MAX_RESOURCES} files`;+ }+ const paths = new Map<string, string>();+ let total = 0;+ for (const { path, size } of files) {+ if (!path.split("/").every(isSafeSegment)) {+ return `its file "${path}" is not a valid skill:// path`;+ }+ if (size > MAX_SKILL_FILE_BYTES) {+ return `its file "${path}" is over ${MAX_SKILL_FILE_BYTES} bytes`;+ }+ total += size;+ const served = !path.includes("/") && isSkillEntryFileName(path) ? SKILL_ENTRY_FILE_NAME : path;+ if (paths.has(served)) return `it has more than one ${SKILL_ENTRY_FILE_NAME}`;+ paths.set(served, path);+ }+ if (!paths.has(SKILL_ENTRY_FILE_NAME)) return `it has no ${SKILL_ENTRY_FILE_NAME}`;+ if (total > MCP_SKILL_MAX_TOTAL_BYTES) {+ return `its files total more than ${MCP_SKILL_MAX_TOTAL_BYTES} bytes`;+ }+ return paths;+}++/**+ * Lists a skill once and reads every file to build its entry. `undefined`+ * when it is not served.+ */+async function snapshotSkill(+ source: SkillFileSource,+ skill: AgentSkillDescription,+): Promise<SkillSnapshot | undefined> {+ const unserved = (reason: string) => {+ warnOnce(`mcpChannel does not serve the skill "${skill.name}": ${reason}.`);+ return undefined;+ };+ const [listed, directories] = await Promise.all([+ source.listFiles(skill.name),+ source.listDirectories(skill.name),+ ]);+ const paths = servedPaths(skill.name, listed, directories);+ if (typeof paths === "string") return unserved(paths);++ const entries = [...paths.entries()].sort(([left], [right]) => comparePaths(left, right));+ // Only `SkillReadError` is deterministic for this build; anything else+ // (a transient asset or disk read failure) propagates so the catalog evicts+ // the pending snapshot and retries on the next request.+ const read = await mapWithConcurrency(entries, READ_CONCURRENCY, async ([, authored]) => {+ try {+ return toServedFile(await source.readFile(skill.name, authored));+ } catch (error) {+ if (error instanceof SkillReadError) return error.message;+ throw error;+ }+ });+ const failed = read.find((file): file is string => typeof file === "string");+ if (failed !== undefined) return unserved(`a file did not read (${failed})`);+ const files = read as ServedFile[];++ const entryIndex = entries.findIndex(([path]) => path === SKILL_ENTRY_FILE_NAME);+ const document = entryDocument(skill, files[entryIndex]!);+ if (document === undefined) {+ return unserved(+ `its ${SKILL_ENTRY_FILE_NAME} is not UTF-8 text with frontmatter that meets the Agent Skills format`,+ );+ }+ files[entryIndex] = document;+ // Sizes are checked again on the bytes read: a file can change between+ // the listing and the read, and the rewritten `SKILL.md` can grow.+ const total = files.reduce((sum, file) => sum + file.bytes.byteLength, 0);+ if (+ total > MCP_SKILL_MAX_TOTAL_BYTES ||+ files.some((file) => file.bytes.byteLength > MAX_SKILL_FILE_BYTES)+ ) {+ return unserved("its files as read are over the size limits");+ }++ const served = new Map<string, SnapshotFile>();+ const resources: McpSkillEntry["resources"][number][] = [];+ for (const [index, [path]] of entries.entries()) {+ const file = files[index]!;+ served.set(path, { mimeType: servedMimeType(path, file), size: file.bytes.byteLength });+ resources.push({+ uri: skillFileUri(skill.name, path),+ digest: `sha256:${createHash("sha256").update(file.bytes).digest("hex")}`,+ size: file.bytes.byteLength,+ });+ }+ return {+ name: skill.name,+ description: document.description,+ document,+ entry: {+ uri: skillFileUri(skill.name, SKILL_ENTRY_FILE_NAME),+ frontmatter: document.frontmatter,+ resources,+ },+ files: served,+ directories: new Set(directories),+ };+}++interface EntryDocument extends ServedFile {+ readonly text: string;+ readonly description: string;+ readonly frontmatter: JsonObject;+}++/**+ * A skill's `SKILL.md` as served: verbatim when its frontmatter has the+ * skill's `name` and a string `description`, otherwise with frontmatter+ * rewritten to carry both. `undefined` when the result does not conform.+ */+function entryDocument(skill: AgentSkillDescription, raw: ServedFile): EntryDocument | undefined {+ if (raw.text === undefined) return undefined;+ const parsed = parseFrontmatterJson(raw.text);+ if (parsed === undefined) return undefined;+ if (+ parsed.present &&+ parsed.data.name === skill.name &&+ typeof parsed.data.description === "string"+ ) {+ return conforming({+ bytes: raw.bytes,+ description: parsed.data.description,+ frontmatter: parsed.data,+ text: raw.text,+ });+ }+ const description =+ typeof parsed.data.description === "string" ? parsed.data.description : skill.description;+ const { name: _name, description: _description, ...rest } = parsed.data;+ const text = `---\n${renderFrontmatter({ name: skill.name, description, ...rest })}---\n${parsed.content}`;+ const reparsed = parseFrontmatterJson(text);+ if (reparsed === undefined || reparsed.data.name !== skill.name) return undefined;+ return conforming({+ bytes: new TextEncoder().encode(text),+ description,+ frontmatter: reparsed.data,+ text,+ });+}++/** Agent Skills `name`: 1-64 lowercase letters, digits, and single inner hyphens. */+const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;++function conforming(entry: EntryDocument): EntryDocument | undefined {+ const { name, description } = entry.frontmatter;+ if (typeof name !== "string" || typeof description !== "string") return undefined;+ if (Array.from(name).length > 64 || !SKILL_NAME_PATTERN.test(name)) return undefined;+ if (description.trim().length === 0 || Array.from(description).length > 1024) return undefined;+ return entry;+}++/**+ * Renders frontmatter as YAML with every key and value in JSON form: JSON is+ * valid YAML flow syntax, so every authored field survives without a YAML+ * serializer, and quoting keeps a name like `true` a string.+ */+function renderFrontmatter(frontmatter: JsonObject): string {+ return Object.entries(frontmatter)+ .map(([key, value]) => {+ const renderedKey = /^[A-Za-z_][A-Za-z0-9_-]*$/u.test(key) ? key : JSON.stringify(key);+ return `${renderedKey}: ${JSON.stringify(value)}\n`;+ })+ .join("");+}++function parseFrontmatterJson(+ text: string,+): { readonly present: boolean; readonly data: JsonObject; readonly content: string } | undefined {+ let data: unknown;+ let file;+ try {+ file = parseFrontmatter(text);+ // JSON as `JSON.stringify` writes it: js-yaml's `Date` timestamps become+ // ISO strings and non-finite numbers `null`, and `JSON.parse` keeps a+ // `__proto__` key as an own property instead of setting the prototype.+ data = JSON.parse(JSON.stringify(file?.data ?? {}));+ } catch {+ return undefined;+ }+ if (data === null || typeof data !== "object" || Array.isArray(data)) return undefined;+ return { content: file?.content ?? text, data: data as JsonObject, present: file !== undefined };+}++/** Direct children of a directory of a served skill; `undefined` if it is not a directory. */+function listDirectory(+ snapshot: SkillSnapshot,+ directory: string | undefined,+): { uri: string; name: string; mimeType: string }[] | undefined {+ // The skill root is always a directory; an empty one lists no children.+ if (directory !== undefined && !snapshot.directories.has(directory)) return undefined;+ const prefix = directory === undefined ? "" : `${directory}/`;+ const children: { uri: string; name: string; mimeType: string }[] = [];+ const add = (path: string, mimeType: string) => {+ const name = path.slice(prefix.length);+ if (!path.startsWith(prefix) || name.includes("/")) return;+ children.push({ uri: skillFileUri(snapshot.name, path), name, mimeType });+ };+ for (const [path, file] of snapshot.files) add(path, file.mimeType);+ for (const path of snapshot.directories) add(path, DIRECTORY_MIME_TYPE);+ return children.sort((left, right) => comparePaths(left.name, right.name));+}++// ---------- URIs ----------++/**+ * Parses `skill://<skill>[/<path>]` strictly. Rejected: other schemes, a+ * query or fragment, whitespace, backslashes, empty segments (so `//` and a+ * trailing `/`), `.` and `..` segments (decoded too), percent-encoded `/`,+ * `\`, or NUL, and malformed percent-encoding.+ */+export function parseSkillUri(+ uri: string,+): { readonly skill: string; readonly path?: string } | undefined {+ if (!uri.startsWith(SKILL_URI_PREFIX)) return undefined;+ const rest = uri.slice(SKILL_URI_PREFIX.length);+ if (/[?#\\\s]/u.test(rest)) return undefined;+ const segments: string[] = [];+ for (const raw of rest.split("/")) {+ let segment: string;+ try {+ segment = decodeURIComponent(raw);+ } catch {+ return undefined;+ }+ if (!isSafeSegment(segment)) return undefined;+ segments.push(segment);+ }+ const [skill, ...path] = segments;+ if (skill === undefined) return undefined;+ return path.length === 0 ? { skill } : { skill, path: path.join("/") };+}++function isSafeSegment(segment: string): boolean {+ return (+ segment.length > 0 &&+ segment !== "." &&+ segment !== ".." &&+ !segment.includes("/") &&+ !segment.includes("\\") &&+ !segment.includes("\0")+ );+}++function skillFileUri(skill: string, path: string): string {+ const encodedPath = path.split("/").map(encodeURIComponent).join("/");+ return `${SKILL_URI_PREFIX}${encodeURIComponent(skill)}/${encodedPath}`;+}++// ---------- Helpers ----------++function rejectCursor(cursor: unknown): void {+ // Every list is returned whole, so the server never issues a cursor.+ if (cursor !== undefined) {+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Unknown cursor.");+ }+}++const MIME_TYPES: ReadonlyMap<string, string> = new Map([+ ["css", "text/css"],+ ["csv", "text/csv"],+ ["gif", "image/gif"],+ ["htm", "text/html"],+ ["html", "text/html"],+ ["jpeg", "image/jpeg"],+ ["jpg", "image/jpeg"],+ ["js", "text/javascript"],+ ["json", "application/json"],+ ["md", "text/markdown"],+ ["mjs", "text/javascript"],+ ["pdf", "application/pdf"],+ ["png", "image/png"],+ ["py", "text/x-python"],+ ["sh", "text/x-shellscript"],+ ["svg", "image/svg+xml"],+ ["ts", "text/typescript"],+ ["txt", "text/plain"],+ ["webp", "image/webp"],+ ["xml", "application/xml"],+ ["yaml", "application/yaml"],+ ["yml", "application/yaml"],+]);++/** MIME type by extension; a text file with an unknown extension is `text/plain`. */+function servedMimeType(path: string, file: ServedFile): string {+ const name = path.slice(path.lastIndexOf("/") + 1);+ const dot = name.lastIndexOf(".");+ const known = dot <= 0 ? undefined : MIME_TYPES.get(name.slice(dot + 1).toLowerCase());+ return known ?? (file.text === undefined ? "application/octet-stream" : "text/plain");+}++function mimeTypeFor(path: string): string {+ return servedMimeType(path, { bytes: new Uint8Array() });+}++async function mapWithConcurrency<T, R>(+ items: readonly T[],+ limit: number,+ map: (item: T) => Promise<R>,+): Promise<R[]> {+ const results: R[] = Array.from({ length: items.length });+ let next = 0;+ const worker = async () => {+ while (next < items.length) {+ const index = next;+ next += 1;+ results[index] = await map(items[index] as T);+ }+ };+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));+ return results;+}diff --git a/packages/eve/src/internal/mcp/streamable-http-server.ts b/packages/eve/src/internal/mcp/streamable-http-server.tsindex 791aabd41..76b2a163b 100644--- a/packages/eve/src/internal/mcp/streamable-http-server.ts+++ b/packages/eve/src/internal/mcp/streamable-http-server.ts@@ -2,6 +2,9 @@ import { context as otelContext } from "#compiled/@opentelemetry/api/index.js";import {createMcpHandler,McpServer,+ type CacheHint,+ type McpJsonObject,+ type McpServerOptions,type McpToolAnnotations,type StandardSchemaIssue,type StandardSchemaWithJSON,@@ -20,6 +23,27 @@ export const MCP_PROTOCOL_VERSION = "2026-07-28";*/export const MCP_REQUEST_BODY_MAX_BYTES = 1024 * 1024;+/**+ * Cache hint for the tool lists, skill lists, and skill reads eve serves.+ * They are fixed per deployment, but clients cache per URL, and a production+ * alias serves a new deployment under the same URL, so the TTL is how long a+ * client may see the old lists after a deploy. `private`: route auth+ * admitted this caller, and a shared cache cannot rerun it for the next one.+ */+export const MCP_LIST_CACHE_HINT = {+ cacheScope: "private",+ ttlMs: 5 * 60 * 1000,+} as const satisfies CacheHint;++/** The cacheable SDK-built results eve answers with {@link MCP_LIST_CACHE_HINT}. */+const CACHE_HINTED_METHODS = [+ "resources/list",+ "resources/read",+ "resources/templates/list",+ "server/discover",+ "tools/list",+] as const;+interface McpToolDefinition<TInputSchema extends StandardSchemaWithJSON = StandardSchemaWithJSON> {readonly name: string;readonly description?: string;@@ -87,6 +111,17 @@ export interface McpServerTool {register(server: McpServer, auth: SessionAuthContext | null): void;}+/**+ * A set of MCP handlers beside the tools, such as skills. Every request+ * builds a fresh server, so `register` runs once per request, after+ * `capabilities` are merged one level deep into the server's own.+ * Declaring a capability obliges `register` to set its handlers.+ */+export interface McpServerFeature {+ readonly capabilities: McpJsonObject;+ register(server: McpServer): void;+}+type InferSchemaOutput<TSchema> =TSchema extends StandardSchemaWithJSON<unknown, infer TOutput> ? TOutput : never;@@ -170,7 +205,9 @@ interface McpStreamableHttpServerOptions {readonly version: string;/** Server-level usage guidance returned from `initialize` and `server/discover`. */readonly instructions?: string;- readonly tools: readonly McpServerTool[];+ /** When set, the server declares `tools`, even for an empty list. */+ readonly tools?: readonly McpServerTool[];+ readonly features?: readonly McpServerFeature[];authenticate(request: Request): Promise<SessionAuthContext | null | Response>;}@@ -183,8 +220,10 @@ interface McpStreamableHttpServerOptions {export function createMcpStreamableHttpServer(options: McpStreamableHttpServerOptions,): (request: Request) => Promise<Response> {- const tools = new Map(options.tools.map((tool) => [tool.name, tool]));- if (tools.size !== options.tools.length) throw new Error("MCP tool names must be unique.");+ const tools = new Map((options.tools ?? []).map((tool) => [tool.name, tool]));+ if (tools.size !== (options.tools?.length ?? 0)) {+ throw new Error("MCP tool names must be unique.");+ }return async (request) => {const auth = await options.authenticate(request);@@ -385,17 +424,31 @@ function readJsonRpcRequestId(body: unknown): string | number | null {}function createServer(- options: Pick<McpStreamableHttpServerOptions, "instructions" | "name" | "version">,+ options: Pick<+ McpStreamableHttpServerOptions,+ "features" | "instructions" | "name" | "tools" | "version"+ >,tools: ReadonlyMap<string, McpServerTool>,auth: SessionAuthContext | null,): McpServer {- const serverOptions: { capabilities: Record<string, unknown>; instructions?: string } = {- capabilities: { tools: { listChanged: false } },+ const capabilities: Record<string, McpJsonObject> =+ options.tools === undefined ? {} : { tools: { listChanged: false } };+ for (const feature of options.features ?? []) {+ for (const [key, value] of Object.entries(feature.capabilities)) {+ capabilities[key] = { ...capabilities[key], ...(value as McpJsonObject) };+ }+ }+ const serverOptions: { -readonly [K in keyof McpServerOptions]: McpServerOptions[K] } = {+ cacheHints: Object.fromEntries(+ CACHE_HINTED_METHODS.map((method) => [method, MCP_LIST_CACHE_HINT]),+ ),+ capabilities,};if (options.instructions !== undefined) serverOptions.instructions = options.instructions;const server = new McpServer({ name: options.name, version: options.version }, serverOptions);for (const tool of tools.values()) tool.register(server, auth);+ for (const feature of options.features ?? []) feature.register(server);return server;}diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.tsindex 62f513869..0297bd704 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts@@ -86,6 +86,7 @@ function createNitroStub(input: { buildDir?: string; dev?: boolean } = {}): Nitrdev: input.dev ?? false,handlers: [],publicAssets: [],+ serverAssets: [],rootDir: "/tmp/weather-agent",virtual: {},},diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex 9ed011215..df6532239 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -20,6 +20,7 @@ import {import { createProductionNitroArtifactsConfig } from "#internal/nitro/host/artifacts-config.js";import { createCompiledSandboxProviderPrunePlugin } from "#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import { createDevelopmentRuntimePrunePlugin } from "#internal/nitro/host/development-runtime-prune-plugin.js";+import { prepareSkillServerAssets } from "#internal/nitro/host/skill-server-assets.js";import { createExtensionScopePlugin } from "#internal/bundler/extension-scope-plugin.js";import { extensionOverridePaths } from "#compiler/extension-mount-bindings.js";import { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";@@ -802,6 +803,18 @@ export async function createProductionApplicationNitro();await prepareEveVersionedCacheDirectory(options.buildDir);+ // Production reads skill files through Nitro server assets; dev reads the+ // compile directory directly (see `createCompiledSkillFileSource`).+ const { manifest, paths } = preparedHost.compileResult;+ const skillServerAssets = await prepareSkillServerAssets({+ stagingDirectory: join(options.buildDir, "eve-skill-assets"),+ skills: manifest.skills.map((skill) => skill.name),+ skillsRoot: join(+ paths.compileDirectoryPath,+ manifest.workspaceResourceRoot.logicalPath,+ "skills",+ ),+ });const nitro = await createNitro({_cli: { command: "build" },buildDir: options.buildDir,@@ -819,6 +832,7 @@ export async function createProductionApplicationNitro(rolldownConfig: bundler.nitroRolldownConfig,rollupConfig: bundler.nitroRollupConfig,rootDir: preparedHost.appRoot,+ serverAssets: skillServerAssets,serverDir: false,traceDeps: bundler.tracedAppDependencies,traceOpts: { nft: { paths: bundler.tracedAppDependencyPaths } },@@ -830,6 +844,12 @@ export async function createProductionApplicationNitro(}),});await writeEveVersionedCacheMetadata(options.buildDir);+ // Nitro always appends a `server` asset for `<rootDir>/assets`. eve reads+ // only its own bases, and reading storage would otherwise start bundling+ // an app's `assets/` directory.+ nitro.options.serverAssets = nitro.options.serverAssets.filter(+ (asset) => asset.baseName !== "server",+ );configureSharedApplicationNitro(nitro, preparedHost);configureNitroStepPlugins(nitro, join(preparedHost.workflowBuildDir, "steps.mjs"));diff --git a/packages/eve/src/internal/nitro/host/skill-server-assets.ts b/packages/eve/src/internal/nitro/host/skill-server-assets.tsnew file mode 100644index 000000000..d6618aa6b--- /dev/null+++ b/packages/eve/src/internal/nitro/host/skill-server-assets.ts@@ -0,0 +1,77 @@+import { createHash } from "node:crypto";+import { mkdir, rm, writeFile } from "node:fs/promises";+import { join, resolve } from "node:path";++import {+ comparePaths,+ createDiskSkillFileSource,+ MAX_SKILL_FILE_BYTES,+ SKILL_FILES_INDEX_KEY,+ SKILL_FILES_INDEX_SERVER_ASSET_BASE,+ SKILL_FILES_SERVER_ASSET_BASE,+ skillFileStorageKey,+ type SkillFilesIndex,+ type SkillFilesIndexEntry,+} from "#channel/skill-files.js";++/** One Nitro `serverAssets` entry. */+export interface SkillServerAssetDirectory {+ readonly baseName: string;+ readonly dir: string;+}++/**+ * Stages the root agent's materialized `skills/` tree as Nitro server assets+ * for a production build, and returns the `serverAssets` entries to register.+ *+ * The listing and bytes come from {@link createDiskSkillFileSource}, the same+ * source dev reads, so both modes agree on which files exist.+ *+ * Nitro picks how to inline a server asset from its file name: text MIME+ * types become UTF-8 strings, which loses bytes that are not valid UTF-8,+ * unstorage decodes any string starting with `base64:`, and an empty string+ * is dropped by Nitro's `r.default || r`. So each shipped file is written as+ * `<stagingDirectory>/files/<sha256>.bin`, which Nitro always inlines as a+ * `Uint8Array`. Identical files share one asset. Real paths, sizes, and+ * digests go into an eve-owned index registered as its own server asset.+ * Files over {@link MAX_SKILL_FILE_BYTES} are indexed by size only, and+ * directories are indexed so empty ones survive the build.+ */+export async function prepareSkillServerAssets(input: {+ /** Build-owned directory the staged assets and the index are written to. */+ readonly stagingDirectory: string;+ readonly skills: readonly string[];+ /** The materialized `skills/` directory of the root agent's workspace resources. */+ readonly skillsRoot: string;+}): Promise<SkillServerAssetDirectory[]> {+ const source = createDiskSkillFileSource(resolve(input.skillsRoot));+ const filesDirectory = join(input.stagingDirectory, "files");+ const indexDirectory = join(input.stagingDirectory, "index");+ await rm(input.stagingDirectory, { force: true, recursive: true });+ await mkdir(filesDirectory, { recursive: true });+ await mkdir(indexDirectory, { recursive: true });++ const index: [string, SkillFilesIndexEntry[], readonly string[]][] = [];+ for (const skill of [...new Set(input.skills)].sort(comparePaths)) {+ const files: SkillFilesIndexEntry[] = [];+ for (const { path, size } of await source.listFiles(skill)) {+ if (size > MAX_SKILL_FILE_BYTES) {+ files.push([path, size, null]);+ continue;+ }+ // Hash and stage the bytes that were read, not a second read of the path.+ const bytes = await source.readFile(skill, path);+ const sha256 = createHash("sha256").update(bytes).digest("hex");+ await writeFile(join(filesDirectory, skillFileStorageKey(sha256)), bytes);+ files.push([path, bytes.byteLength, sha256]);+ }+ index.push([skill, files, await source.listDirectories(skill)]);+ }++ const skillFilesIndex: SkillFilesIndex = { version: 1, skills: index };+ await writeFile(join(indexDirectory, SKILL_FILES_INDEX_KEY), JSON.stringify(skillFilesIndex));+ return [+ { baseName: SKILL_FILES_INDEX_SERVER_ASSET_BASE, dir: indexDirectory },+ { baseName: SKILL_FILES_SERVER_ASSET_BASE, dir: filesDirectory },+ ];+}diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex c49a16760..959040936 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -21,6 +21,7 @@ import {attachRouteChannelName,attachRemoteAgentStreamHeadersResolver,attachRouteSessionCreator,+ attachSkillFileSource,} from "#internal/nitro/routes/channel-route-context.js";import {type NitroArtifactsConfig,@@ -270,6 +271,7 @@ async function buildRouteArgs(});const to = createCrossChannelToFn(bundle.runtime, toCrossChannelTargets(bundle.channels));+ const agent = createAgentDescriptionRouteArgs(() => resolveNitroCompiledArtifactsSource(config));const args = attachRouteSessionCreator(attachHomeRouteMetadata(attachRouteChannelName(@@ -277,7 +279,7 @@ async function buildRouteArgs({attachSession,...channelOperations,- ...createAgentDescriptionRouteArgs(() => resolveNitroCompiledArtifactsSource(config)),+ ...agent.args,invokeTool: createRouteInvokeTool({agentName: bundle.agentName,config,@@ -311,6 +313,7 @@ async function buildRouteArgs(requestId,}),);+ attachSkillFileSource(args, agent.skillFiles);if (bundle.resolveRemoteAgentStreamHeaders !== undefined) {attachRemoteAgentStreamHeadersResolver(args, bundle.resolveRemoteAgentStreamHeaders);}diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.tsindex 7006fb851..f7d770c67 100644--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts@@ -1,4 +1,5 @@import type { RouteHandlerArgs } from "#channel/routes.js";+import type { SkillFileSource } from "#channel/skill-files.js";import type { RunHandle, RunInput } from "#channel/types.js";type AgentInfoRouteResponse = () => Promise<Response>;@@ -25,6 +26,7 @@ const homeRouteMetadataKey = "__eveHomeRouteMetadata";const routeChannelNameKey = "__eveRouteChannelName";const remoteAgentStreamHeadersResolverKey = "__eveRemoteAgentStreamHeadersResolver";const routeSessionCreatorKey = "__eveRouteSessionCreator";+const skillFileSourceKey = "__eveSkillFileSource";type InternalRouteArgs = RouteHandlerArgs & {[agentInfoRouteResponseKey]?: AgentInfoRouteResponse;@@ -32,6 +34,7 @@ type InternalRouteArgs = RouteHandlerArgs & {[routeChannelNameKey]?: string;[remoteAgentStreamHeadersResolverKey]?: RemoteAgentStreamHeadersResolver;[routeSessionCreatorKey]?: RouteSessionCreator;+ [skillFileSourceKey]?: SkillFileSource;};export function attachRouteChannelName<TArgs extends RouteHandlerArgs>(@@ -107,3 +110,18 @@ export function readRemoteAgentStreamHeadersResolver(const routeArgs: InternalRouteArgs = args;return routeArgs[remoteAgentStreamHeadersResolverKey];}++/** The agent's skill files behind `readSkill`, for channels that serve files they already listed. */+export function attachSkillFileSource<TArgs extends RouteHandlerArgs>(+ args: TArgs,+ files: SkillFileSource,+): TArgs {+ const routeArgs: InternalRouteArgs = args;+ routeArgs[skillFileSourceKey] = files;+ return args;+}++export function readSkillFileSource(args: RouteHandlerArgs): SkillFileSource | undefined {+ const routeArgs: InternalRouteArgs = args;+ return routeArgs[skillFileSourceKey];+}diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.tsindex 0f629eb7c..0f3c9fc6a 100644--- a/packages/eve/src/internal/testing/app-harness.ts+++ b/packages/eve/src/internal/testing/app-harness.ts@@ -265,6 +265,7 @@ export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Prosession.bundleCache.clear();session.bundleCacheKeyBySourceKey.clear();sandboxes.clear();+ session.describedAgents.clear();}async function executeTool(diff --git a/packages/eve/src/internal/testing/channel-conformance/harness.ts b/packages/eve/src/internal/testing/channel-conformance/harness.tsindex ad2fdfdc0..15c80d18d 100644--- a/packages/eve/src/internal/testing/channel-conformance/harness.ts+++ b/packages/eve/src/internal/testing/channel-conformance/harness.ts@@ -739,6 +739,8 @@ async function converse(attachSession,describe: unsupported("describe"),invokeTool: unsupported("invokeTool"),+ listSkillFiles: unsupported("listSkillFiles"),+ readSkill: unsupported("readSkill"),params,requestIp: null,to: unsupported("to"),diff --git a/packages/eve/src/internal/testing/mocks/mock-route-args.ts b/packages/eve/src/internal/testing/mocks/mock-route-args.tsindex 6992edb1b..55347adfa 100644--- a/packages/eve/src/internal/testing/mocks/mock-route-args.ts+++ b/packages/eve/src/internal/testing/mocks/mock-route-args.ts@@ -1,7 +1,10 @@import type { RouteHandlerArgs } from "#channel/routes.js";/** The agent route args, for tests whose routes never call them. */-export function mockAgentRouteArgs(): Pick<RouteHandlerArgs, "describe" | "invokeTool"> {+export function mockAgentRouteArgs(): Pick<+ RouteHandlerArgs,+ "describe" | "invokeTool" | "listSkillFiles" | "readSkill"+> {return {describe: async () => {throw new Error("describe() is unavailable in this test.");@@ -9,5 +12,11 @@ export function mockAgentRouteArgs(): Pick<RouteHandlerArgs, "describe" | "invokinvokeTool: async () => {throw new Error("invokeTool() is unavailable in this test.");},+ listSkillFiles: async () => {+ throw new Error("listSkillFiles() is unavailable in this test.");+ },+ readSkill: async () => {+ throw new Error("readSkill() is unavailable in this test.");+ },};}diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex b41a79a85..a5c1b5385 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -43,6 +43,8 @@ export {type RouteDefinition,type RouteHandlerArgs,type AgentDescription,+ type AgentSkillDescription,+ type AgentSkillFileDescription,type AgentToolDescription,type InvokeToolFn,type InvokeToolOptions,diff --git a/packages/eve/src/public/channels/mcp-tools-tracing.integration.test.ts b/packages/eve/src/public/channels/mcp-tools-tracing.integration.test.tsindex 6a902eb97..954a23092 100644--- a/packages/eve/src/public/channels/mcp-tools-tracing.integration.test.ts+++ b/packages/eve/src/public/channels/mcp-tools-tracing.integration.test.ts@@ -189,7 +189,7 @@ async function call(request: Request): Promise<{ status: number; body: any }> {const base: RouteHandlerArgs = {...mockAgentRouteArgs(),attachSession: unavailable,- describe: async () => ({ name: "compiled-agent", tools: descriptions }),+ describe: async () => ({ name: "compiled-agent", skills: [], tools: descriptions }),from: unavailable,invokeTool: (name, input, options) => invokeTool(runtime, name, input, options),params: {},diff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.tsindex bbad7b8bd..8f5067d94 100644--- a/packages/eve/src/public/channels/mcp.test.ts+++ b/packages/eve/src/public/channels/mcp.test.ts@@ -1,13 +1,15 @@import { describe, expect, it, vi } from "vitest";-import type { AgentToolDescription } from "#channel/agent-description.js";+import type { AgentDescription, AgentToolDescription } from "#channel/agent-description.js";import type { InvokeToolFn, InvokeToolResult } from "#channel/invoke-tool.js";import type { SessionAuthContext } from "#channel/types.js";import type { RouteHandlerArgs } from "#channel/routes.js";+import type { SkillFileSource } from "#channel/skill-files.js";import {attachAgentInfoRouteResponse,attachRouteChannelName,attachRouteSessionCreator,+ attachSkillFileSource,} from "#internal/nitro/routes/channel-route-context.js";import { MCP_PROTOCOL_VERSION } from "#internal/mcp/streamable-http-server.js";import { ForbiddenError, none, oauthResource, withAuthChallenges } from "#public/channels/auth.js";@@ -522,7 +524,7 @@ describe("mcpChannel tools", () => {const post = channel.routes[1]!;if (post.transport === "websocket") throw new Error("expected HTTP route");const args = routeArgs(vi.fn(), {- describe: async () => ({ name: "compiled-agent", tools }),+ describe: async () => ({ name: "compiled-agent", skills: [], tools }),invokeTool,});return async (method: string, params?: unknown) =>@@ -561,10 +563,51 @@ describe("mcpChannel tools", () => {expect(await names(serve({}))).toHaveLength(4);expect(() => mcpChannel({ agent: false, auth: none() })).toThrow(- "mcpChannel publishes nothing with agent and tools both false. Enable one.",+ "mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.",);});+ it("describes once per request, and serves skills only from the route's skill files", async () => {+ const describe = vi.fn<() => Promise<AgentDescription>>(async () => ({+ name: "compiled-agent",+ skills: [{ description: "Runs the kennel.", name: "handbook" }],+ tools: [lookup],+ }));+ const files: SkillFileSource = {+ listFiles: async () => [{ path: "SKILL.md", size: 5 }],+ listDirectories: async () => [],+ readFile: async () => new TextEncoder().encode("Body\n"),+ };+ const channel = mcpChannel({ agent: false, auth: () => principal, skills: true, tools: true });+ const post = channel.routes[1]!;+ if (post.transport === "websocket") throw new Error("expected HTTP route");+ const rpc = async (method: string, args: RouteHandlerArgs) =>+ (await jsonRpcResponse(+ await post.handler(mcpRequest({ id: 1, jsonrpc: "2.0", method }), args),+ )) as { result?: Record<string, any>; error?: object };++ const args = attachSkillFileSource(routeArgs(vi.fn(), { describe }), files);+ expect(+ (await rpc("tools/list", args)).result!.tools.map((t: { name: string }) => t.name),+ ).toEqual(["lookup"]);+ expect(describe).toHaveBeenCalledTimes(1);+ expect((await rpc("skills/list", args)).result!.skills).toEqual([+ expect.objectContaining({ uri: "skill://handbook/SKILL.md" }),+ ]);+ expect(describe).toHaveBeenCalledTimes(2);++ // Without the route's skill files the channel cannot serve skills; a+ // tools-only channel never needs them and never touches skill storage.+ const bare = routeArgs(vi.fn(), { describe });+ const response = await post.handler(+ mcpRequest({ id: 1, jsonrpc: "2.0", method: "tools/list" }),+ bare,+ );+ expect(response.status).toBe(500);+ const toolsOnly = serve({ agent: false, tools: true });+ expect((await toolsOnly("tools/list")).result!.tools).toHaveLength(3);+ });+it("returns non-object output as structured content when the tool declares a schema", async () => {const count: AgentToolDescription = {approval: false,@@ -662,7 +705,7 @@ describe("mcpChannel tools", () => {overrides: { createSession?: () => Promise<never>; invokeTool?: InvokeToolFn },) {const args = routeArgs(overrides.createSession, {- describe: async () => ({ name: "compiled-agent", tools: [note] }),+ describe: async () => ({ name: "compiled-agent", skills: [], tools: [note] }),invokeTool: overrides.invokeTool,});const route = mcpChannel({ auth: () => principal, tools: true, ...options }).routes[1]!;diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsindex ad015356c..b42ee6aea 100644--- a/packages/eve/src/public/channels/mcp.ts+++ b/packages/eve/src/public/channels/mcp.ts@@ -23,12 +23,14 @@ import {} from "#internal/mcp/forwarded-principal-header.js";import type { TrustedForwarders } from "#channel/forwarded-principal.js";import type { SessionAuthContext } from "#channel/types.js";+import { createMcpSkillsFeature } from "#internal/mcp/skills.js";import { validateMcpHttpRequest, validateMcpMetadataRequest } from "#internal/mcp/http-security.js";import {createMcpStreamableHttpServer,defineMcpTool,McpToolOperationError,type McpCallToolResult,+ type McpServerFeature,type McpServerTool,} from "#internal/mcp/streamable-http-server.js";import {@@ -47,6 +49,7 @@ import {readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,+ readSkillFileSource,} from "#internal/nitro/routes/channel-route-context.js";export interface McpChannelInput {/** Existing eve route-auth policy. Use `none()` for explicit public access. */@@ -55,7 +58,7 @@ export interface McpChannelInput {readonly route?: string;/*** Serve the `agent_*` tools, which start and follow a durable agent task.- * With `false`, the channel serves only the tools `tools` publishes.+ * With `false`, the channel serves only what `tools` and `skills` publish.* @default true*/readonly agent?: boolean;@@ -76,17 +79,25 @@ export interface McpChannelInput {* caller. Omit to refuse any request carrying the header with 403.*/readonly trustedForwarders?: TrustedForwarders;+ /**+ * Also serve the agent's skills as SEP-2640 skills under `skill://`+ * (`skills/list`, `skills/get`, and the `resources/*` methods), readable+ * by every route-authenticated caller.+ * @default false+ */+ readonly skills?: boolean;}-/** Public MCP channel publishing this agent's `agent_*` tools and, optionally, its own tools. */+/** Public MCP channel publishing this agent's `agent_*` tools and, optionally, its tools and skills. */export type McpChannel = Channel;/*** Publishes this agent as a stateless Streamable HTTP MCP server.** This channel owns MCP transport, durable eve invocation through the- * `agent_*` tools (unless `agent: false`), and, with `tools: true`, the- * agent's invocable tools, each call run through `invokeTool`. It reuses+ * `agent_*` tools (unless `agent: false`), with `tools: true` the agent's+ * invocable tools, each call run through `invokeTool`, and with+ * `skills: true` the agent's skills and their files. It reuses* eve's inbound auth strategies and recognizes `oauthResource(...)` metadata* when OAuth discovery is needed.* The file containing this channel must be `agent/channels/mcp.ts`.@@ -95,9 +106,15 @@ export function mcpChannel(input: McpChannelInput): McpChannel {if (input?.auth === undefined) {throw new Error("mcpChannel requires auth. Use none() for explicit public access.");}- const publish: McpPublishOptions = { agent: input.agent ?? true, tools: input.tools ?? false };- if (!publish.agent && !publish.tools) {- throw new Error("mcpChannel publishes nothing with agent and tools both false. Enable one.");+ const publish: McpPublishOptions = {+ agent: input.agent ?? true,+ skills: input.skills ?? false,+ tools: input.tools ?? false,+ };+ if (!publish.agent && !publish.tools && !publish.skills) {+ throw new Error(+ "mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.",+ );}const path = input.route ?? "/eve/v1/mcp";const oauth = readOAuthResourceOptions(input.auth);@@ -366,6 +383,7 @@ async function authenticateMcpRequest(interface McpPublishOptions {readonly agent: boolean;+ readonly skills: boolean;readonly tools: boolean;}@@ -407,19 +425,31 @@ async function handleMcpRequest(auth.authenticator === "none" && auth.principalType === "anonymous",): [];- const publishedTools = publish.tools- ? createPublishedTools({- invokeTool: args.invokeTool,- principals,- reserved: new Set(agentTools.map((tool) => tool.name)),- tools: (await args.describe()).tools,- })- : [];+ // One `describe()` serves both the published tools and the skill catalog.+ const described = publish.tools || publish.skills ? await args.describe() : undefined;+ const publishedTools =+ publish.tools && described !== undefined+ ? createPublishedTools({+ invokeTool: args.invokeTool,+ principals,+ reserved: new Set(agentTools.map((tool) => tool.name)),+ tools: described.tools,+ })+ : [];+ const features: McpServerFeature[] = [];+ if (publish.skills && described !== undefined) {+ const files = readSkillFileSource(args);+ if (files === undefined) {+ return Response.json({ error: "MCP requires agent route context." }, { status: 500 });+ }+ features.push(createMcpSkillsFeature({ files, skills: described.skills }));+ }return await createMcpStreamableHttpServer({authenticate: async () => auth,+ features,instructions: publish.agent ? MCP_SERVER_INSTRUCTIONS : undefined,name: agentInfo.agent.name,- tools: [...agentTools, ...publishedTools],+ tools: publish.agent || publish.tools ? [...agentTools, ...publishedTools] : undefined,version: resolveInstalledPackageInfo().version,})(request);}diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex 05e81f58f..429ce504d 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -57,7 +57,12 @@ export type {ChannelSource,};export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";-export type { AgentDescription, AgentToolDescription } from "#channel/agent-description.js";+export type {+ AgentDescription,+ AgentSkillDescription,+ AgentSkillFileDescription,+ AgentToolDescription,+} from "#channel/agent-description.js";export type { InvokeToolFn, InvokeToolOptions, InvokeToolResult } from "#channel/invoke-tool.js";export { DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, WS } from "#channel/routes.js";export type {diff --git a/packages/eve/src/runtime/sessions/runtime-session.ts b/packages/eve/src/runtime/sessions/runtime-session.tsindex df99be5a7..15aadc2e0 100644--- a/packages/eve/src/runtime/sessions/runtime-session.ts+++ b/packages/eve/src/runtime/sessions/runtime-session.ts@@ -1,5 +1,6 @@import { AsyncLocalStorage } from "node:async_hooks";+import type { DescribedAgent } from "#channel/agent-description.js";import type { BundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";@@ -33,6 +34,15 @@ export interface RuntimeSession {* changes.*/readonly bundleCacheKeyBySourceKey: Map<string, string>;+ /**+ * Agents as channel routes describe them, keyed by the stable source key+ * and tagged with the versioned cache key they were loaded under, so a+ * recompile under the same app root replaces the entry.+ */+ readonly describedAgents: Map<+ string,+ { readonly agent: Promise<DescribedAgent>; readonly version: string }+ >;}/**@@ -43,6 +53,7 @@ export function createRuntimeSession(id: string = "test-session"): RuntimeSessiobundleCache: new Map(),bundleCacheKeyBySourceKey: new Map(),compiledArtifacts: null,+ describedAgents: new Map(),id,};}@@ -54,11 +65,13 @@ export function setRuntimeSessionCompiledArtifacts(const installed = session.compiledArtifacts;const snapshotChanged = installed === null || !isSameCompiledArtifactSnapshot(installed, input);- // Resolved bundles retain references into the installed snapshot, so a- // replacement must not inherit caches populated by the prior deployment.+ // Resolved bundles and described agents retain references into the+ // installed snapshot, so a replacement must not inherit caches populated+ // by the prior deployment.if (snapshotChanged) {session.bundleCache.clear();session.bundleCacheKeyBySourceKey.clear();+ session.describedAgents.clear();}session.compiledArtifacts = input;