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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion cloudflare/library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ export class ArtifactLibrary extends DurableObject<unknown> {
recordServe(input: {
workspace: string; name: string; source: string; server_source?: string | null; project?: ArtifactProject; runtime: string;
initial_state: Record<string, unknown>; mode: "live" | "replay" | "preview";
pane_id?: string; session_id?: string; version_id?: string; compiled_id?: string;
pane_id?: string; session_id?: string; version_id?: string; compiled_id?: string; record_event?: boolean;
}) {
const workspace = workspaceName(input.workspace); const name = artifactName(input.name);
const source = sourceText(input.source); const runtime = runtimeName(input.runtime);
Expand Down Expand Up @@ -414,6 +414,7 @@ export class ArtifactLibrary extends DurableObject<unknown> {
} else {
version = this.capture(workspace, name, source, server_source, project, runtime, "served", null, false, input.compiled_id);
}
if (input.record_event === false) return { version, event: null };
const event: ServeEvent = {
id: uuid(), version_id: version.id, served_at: now(), pane_id: input.pane_id ?? null,
session_id: input.session_id ?? null, mode: input.mode, initial_state, runtime,
Expand Down
11 changes: 7 additions & 4 deletions cloudflare/managed-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import type { ArtifactHttpRequest } from "../src/httpTypes";
import type { ArtifactFileRequest } from "../src/sdk/files";
import type { GalleryArtifact, GalleryData } from "../src/gallery/types";
import { CloudArtifactService } from "./service";
import { workspaceTool } from "./workspace-tools";
import { parseProjectArchive } from "../src/project-archive";
import { ownershipName } from "./ownership";

const text = (value: unknown): CallToolResult => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
type Selection = { name?: string; version_id?: string; event_id?: string };
type Selection = { workspace?: string; name?: string; version_id?: string; event_id?: string };

/** Management requests select an owner; execution continues on immutable storage. */
export class ManagedArtifactService {
Expand Down Expand Up @@ -44,7 +45,7 @@ export class ManagedArtifactService {

private async callSelectedTool(target: ArtifactTarget, name: string, args: Record<string, unknown>) {
const changesGallery = /^(artifact|script)_(write|edit|restore|remix|import|open|link)$/.test(name);
try { return await this.physical(target).callTool(name, args); }
try { return await this.physical(target).callTool(name, { ...args, workspace: target.workspace }); }
finally {
// A failed compile may still have saved a draft. Resolve current ownership
// after the operation, including writes admitted before a library move.
Expand All @@ -66,6 +67,8 @@ export class ManagedArtifactService {
}

async callTool(name: string, args: Record<string, unknown>): Promise<CallToolResult> {
if (["artifacts_library", "artifacts_working", "artifacts_search", "artifacts_mentions"].includes(name)) return workspaceTool(this, name, args);
if (name === "artifacts_preview") name = "artifact_open";
if (name.startsWith("app_")) return this.nativeTool(name, args);
if (["artifact_guide", "script_guide", "plugins_list", "plugin_guide", "artifact_plugin_call"].includes(name)) return this.physical({ libraryKey: this.libraryKey, workspace: this.workspace }).callTool(name, args);
const kind = name.startsWith("script_") ? "script" : name === "artifact_link" ? args.kind as "artifact" | "script" : "artifact";
Expand All @@ -75,7 +78,7 @@ export class ManagedArtifactService {
if (!history) for (const row of rows) Object.assign(row, await this.linkDetails(kind, row.workspace, kind === "artifact" ? row.id! : row.name));
return text({ [history ? "versions" : kind === "script" ? "scripts" : "artifacts"]: rows, next_offset: rows.length === 100 ? offset + 100 : null });
}
const selection = this.selection(kind, { name: args.name as string | undefined, version_id: args.version_id as string | undefined });
const selection = this.selection(kind, { name: args.name as string | undefined, version_id: args.version_id as string | undefined, ...(typeof args.workspace === "string" ? { workspace: args.workspace } : {}) });
if (name.endsWith("_import")) {
parseProjectArchive(args.archive, kind);
const target = await this.links.admit(this.selection(kind, { name: args.new_name as string }), true);
Expand Down Expand Up @@ -125,7 +128,7 @@ export class ManagedArtifactService {
async request(selection: Selection, request: ArtifactHttpRequest) { return (await this.service("artifact", selection)).request(selection, request); }
async fileRequest(selection: Selection, request: ArtifactFileRequest) { return (await this.service("artifact", selection)).fileRequest(selection, request); }
async preview(snapshot: Awaited<ReturnType<CloudArtifactService["snapshot"]>>) {
const selection = snapshot.version_id ? { version_id: snapshot.version_id, event_id: (snapshot as { event_id?: string | null }).event_id ?? undefined } : { name: snapshot.name };
const selection = snapshot.version_id ? { workspace: snapshot.workspace, version_id: snapshot.version_id, event_id: (snapshot as { event_id?: string | null }).event_id ?? undefined } : { workspace: snapshot.workspace, name: snapshot.name };
const service = await this.service("artifact", selection);
// The gallery's snapshot and preview are separate calls. Re-read after fresh
// ownership admission instead of reusing a possibly moved/recreated draft.
Expand Down
31 changes: 25 additions & 6 deletions cloudflare/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,37 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
import {
CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema,
ListResourceTemplatesRequestSchema, ReadResourceRequestSchema,
ErrorCode, McpError,
ErrorCode, McpError, type CallToolResult,
} from "@modelcontextprotocol/sdk/types.js";
import { ARTIFACTS_APP_URI, ARTIFACTS_RESOURCE } from "../src/mcp/app-contract";
import shell from "../dist/cloudflare/mcp-app.json";
import * as validators from "../dist/cloudflare/tool-validators.js";
import { artifactFileResult } from "../src/mcp/file-contract";
import { clientSupportsApps, toolsForClient } from "../src/mcp/host-contract";
import { CLOUD_MCP_TOOLS } from "./tool-contract";
import type { CloudArtifactService } from "./service";

export async function handleCloudMcp(request: Request, service: Pick<CloudArtifactService, "callTool" | "fileStorage">, parsedBody?: unknown): Promise<Response> {
export async function handleCloudMcp(request: Request, service: Pick<CloudArtifactService, "callTool" | "fileStorage" | "snapshot">, parsedBody?: unknown): Promise<Response> {
// Low-level SDK registration lets local and hosted transports share the same
// JSON schemas, with argument validators generated from them at build time.
const server = new Server({ name: "artifacts", version: "0.1.0" }, { capabilities: { tools: {}, resources: {} } });
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: CLOUD_MCP_TOOLS }));
const resource = service.fileStorage ? { ...ARTIFACTS_RESOURCE, _meta: { ui: { ...ARTIFACTS_RESOURCE._meta.ui,
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: toolsForClient(CLOUD_MCP_TOOLS, server.getClientCapabilities() === undefined || clientSupportsApps(server.getClientCapabilities())) }));
const resource = service.fileStorage ? { ...ARTIFACTS_RESOURCE, _meta: { ...ARTIFACTS_RESOURCE._meta, ui: { ...ARTIFACTS_RESOURCE._meta.ui,
csp: { ...ARTIFACTS_RESOURCE._meta.ui.csp, connectDomains: [service.fileStorage.origin] },
} } } : ARTIFACTS_RESOURCE;
server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: [resource] }));
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates: [] }));
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates: [{ uriTemplate: "artifact://project?workspace={workspace}&name={name}", name: "Artifact source", description: "Read an artifact source snapshot in the authenticated library.", mimeType: "application/json" }] }));
server.setRequestHandler(ReadResourceRequestSchema, async ({ params }) => {
if (params.uri.startsWith("artifact://")) {
const uri = new URL(params.uri);
if (uri.hostname !== "project" || uri.pathname || !uri.searchParams.get("workspace") || !uri.searchParams.get("name")) throw new McpError(ErrorCode.InvalidParams, "Invalid artifact resource");
// Admission is repeated for every read; a previously issued mention URI is
// descriptive context, never an authorization capability.
const selection = { workspace: uri.searchParams.get("workspace")!, name: uri.searchParams.get("name")!, ...(uri.searchParams.has("version_id") ? { version_id: uri.searchParams.get("version_id")! } : {}) };
const snapshot = await service.snapshot(selection);
if (snapshot.name !== selection.name) throw new McpError(ErrorCode.InvalidParams, "Artifact version does not match name");
return { contents: [{ uri: params.uri, mimeType: "application/json", text: JSON.stringify({ name: snapshot.name, workspace: snapshot.workspace, version_id: snapshot.version_id ?? null, revision_token: snapshot.revision_token, description: `React artifact ${snapshot.name} in workspace ${snapshot.workspace}`, source: snapshot.source, server_source: snapshot.server_source, project: snapshot.project }) }] };
}
if (params.uri !== ARTIFACTS_APP_URI) throw new McpError(ErrorCode.InvalidParams, "Unknown resource");
return { contents: [{ ...resource, text: shell }] };
});
Expand All @@ -30,7 +42,14 @@ export async function handleCloudMcp(request: Request, service: Pick<CloudArtifa
const validate = validators[params.name as keyof typeof validators];
const args = params.arguments ?? {};
if (!validate(args)) throw new McpError(ErrorCode.InvalidParams, "Invalid tool arguments", validate.errors);
try { return await service.callTool(params.name, args); }
try {
const result: CallToolResult = params.name === "artifacts_file" ? artifactFileResult(args) : await service.callTool(params.name, args);
if (server.getClientCapabilities() !== undefined && !clientSupportsApps(server.getClientCapabilities())) {
const { _meta, ...plain } = result;
return plain;
}
return result;
}
catch (error) {
return { content: [{ type: "text" as const, text: error instanceof Error ? error.message : String(error) }], isError: true };
}
Expand Down
Loading
Loading