mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-17 23:26:02 +00:00
mcp: artcraft://models/{kind} resource and the plan_generation prompt
src/mcp/resources.ts registers the catalogue as a resource template for principals with read:catalog — five listable documents (one per kind), each read through list_models and served as JSON. src/mcp/prompts.ts registers plan_generation: given a brief (and optionally a kind), walk list_models → estimate_cost → get_credit_balance and recommend, without generating anything. Tests (3, via the SDK's in-memory client): template and resource listing, a JSON read, an unknown kind refused; the resource withheld without read:catalog; the prompt listed and rendered with its steps. pnpm check: typecheck, eslint, prettier, 231 tests passing. Claude-Session: https://claude.ai/code/session_01H3gfN2NCx3hBXSrZXYHUQ3
This commit is contained in:
1 parent
110f47085a
commit
a33bec94da
4 files changed
+182
-1
No files matched your search
@@ -0,0 +1,54 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
|
||||
import { GENERATION_KINDS } from "./tools/list-models";
|
||||
|
||||
/**
|
||||
* `plan_generation` — one prompt that exercises the whole read-only surface: given a brief,
|
||||
* pick candidate models, price each, check the balance, and recommend. It spends nothing.
|
||||
*/
|
||||
|
||||
export const PLAN_GENERATION_PROMPT = "plan_generation";
|
||||
|
||||
export function registerPlanGenerationPrompt(server: McpServer): void {
|
||||
server.registerPrompt(
|
||||
PLAN_GENERATION_PROMPT,
|
||||
{
|
||||
title: "Plan a generation",
|
||||
description:
|
||||
"Given a creative brief, work out which Artcraft models could produce it, what each " +
|
||||
"would cost, and whether the user's credits cover it — then recommend one. Read-only.",
|
||||
argsSchema: {
|
||||
brief: z.string().describe("What the user wants to make, in their words."),
|
||||
kind: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
`Optional: ${GENERATION_KINDS.join(", ")}. Inferred from the brief when omitted.`,
|
||||
),
|
||||
},
|
||||
},
|
||||
({ brief, kind }) => ({
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: {
|
||||
type: "text",
|
||||
text: [
|
||||
`Plan an Artcraft generation for this brief: "${brief}".`,
|
||||
kind
|
||||
? `The kind of output is ${kind}.`
|
||||
: `First decide which kind of output fits (${GENERATION_KINDS.join(", ")}).`,
|
||||
"Steps:",
|
||||
"1. Call list_models for that kind and shortlist two or three models whose capabilities suit the brief (check supported inputs, aspect ratios, durations, batch sizes).",
|
||||
"2. For each shortlisted model, call estimate_cost with the parameters the brief implies, using only option values the model's capabilities allow.",
|
||||
"3. Call get_credit_balance to see what the user can spend.",
|
||||
"4. Recommend one model and one set of parameters, stating the estimated cost, whether the balance covers it, and any trade-off (quality, watermark, refund policy). Remind the user that estimates are public pricing and their plan may lower them.",
|
||||
"Do not generate anything; this is a plan.",
|
||||
].join("\n"),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
|
||||
import { hasScope } from "../tokens/principal";
|
||||
import { GENERATION_KINDS, listModels } from "./tools/list-models";
|
||||
import type { ToolContext } from "./tools/types";
|
||||
import { ToolFailure, UpstreamSessionInvalid } from "./tools/types";
|
||||
|
||||
/**
|
||||
* `artcraft://models/{kind}` — the model catalogue as a readable resource, for clients that
|
||||
* prefetch context rather than calling tools (Claude Code, Cursor). Same data as list_models,
|
||||
* same scope; registered only when the principal may read the catalogue.
|
||||
*/
|
||||
|
||||
export const MODELS_RESOURCE_TEMPLATE = "artcraft://models/{kind}";
|
||||
|
||||
export function registerCatalogueResource(server: McpServer, context: ToolContext): boolean {
|
||||
if (!hasScope(context.principal, listModels.requiredScope)) return false;
|
||||
|
||||
const template = new ResourceTemplate(MODELS_RESOURCE_TEMPLATE, {
|
||||
list: () => ({
|
||||
resources: GENERATION_KINDS.map((kind) => ({
|
||||
uri: `artcraft://models/${kind}`,
|
||||
name: `${kind} models`,
|
||||
title: `Artcraft ${kind} models`,
|
||||
description: `Every ${kind} generation model Artcraft offers, with capabilities and option lists.`,
|
||||
mimeType: "application/json",
|
||||
})),
|
||||
}),
|
||||
});
|
||||
|
||||
server.registerResource(
|
||||
"models",
|
||||
template,
|
||||
{
|
||||
title: "Artcraft model catalogues",
|
||||
description:
|
||||
"The generation models Artcraft offers, one document per kind (image, video, audio, " +
|
||||
"mesh, splat), as JSON. The same data list_models returns.",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
async (uri, variables) => {
|
||||
const kind = String(variables.kind);
|
||||
if (!GENERATION_KINDS.some((known) => known === kind)) {
|
||||
throw new Error(
|
||||
`Unknown catalogue "${kind}"; expected one of ${GENERATION_KINDS.join(", ")}.`,
|
||||
);
|
||||
}
|
||||
try {
|
||||
const result = await listModels.handler(context, {
|
||||
kind: kind as (typeof GENERATION_KINDS)[number],
|
||||
});
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.href,
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(result.structured, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof ToolFailure || error instanceof UpstreamSessionInvalid) {
|
||||
throw new Error(error.message, { cause: error });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import type { z } from "zod";
|
||||
|
||||
import { hasScope, type Principal } from "../tokens/principal";
|
||||
import type { UpstreamClient } from "../upstream/client";
|
||||
import { registerPlanGenerationPrompt } from "./prompts";
|
||||
import { registerCatalogueResource } from "./resources";
|
||||
import { estimateCost } from "./tools/estimate-cost";
|
||||
import { getAccount } from "./tools/get-account";
|
||||
import { getCreditBalance } from "./tools/get-credit-balance";
|
||||
@@ -85,6 +87,9 @@ export function createMcpServer(deps: McpServerDeps): McpServer {
|
||||
// "method not found" — so in that case declare the capability and answer ourselves.
|
||||
if (registered === 0) installEmptyToolHandlers(server);
|
||||
|
||||
registerCatalogueResource(server, context);
|
||||
registerPlanGenerationPrompt(server);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,12 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PLAN_GENERATION_PROMPT } from "../../src/mcp/prompts";
|
||||
import { MODELS_RESOURCE_TEMPLATE } from "../../src/mcp/resources";
|
||||
import { createMcpServer, SERVER_INFO } from "../../src/mcp/server";
|
||||
import { principalFromProps } from "../../src/tokens/principal";
|
||||
import { createUpstreamClient } from "../../src/upstream/client";
|
||||
import { modelsResponse } from "../../fake-upstream/src/catalogue";
|
||||
import { fixture } from "../helpers/contract";
|
||||
|
||||
/** Drives the server the way a real MCP client does — over the protocol, in memory. */
|
||||
@@ -43,7 +46,12 @@ async function connect(scopes: string[], status = 200) {
|
||||
credential: principal.credential,
|
||||
fetch: (input) => {
|
||||
const path = new URL(new Request(input).url).pathname;
|
||||
const body = path.startsWith("/v1/credits") ? CREDITS : NO_SUBSCRIPTION;
|
||||
const modelsKind = /^\/v1\/omni_gen\/models\/(\w+)$/.exec(path)?.[1];
|
||||
const body = modelsKind
|
||||
? modelsResponse(modelsKind as Parameters<typeof modelsResponse>[0], "all")
|
||||
: path.startsWith("/v1/credits")
|
||||
? CREDITS
|
||||
: NO_SUBSCRIPTION;
|
||||
return Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify(status === 200 ? body : { success: false, error_code: status }),
|
||||
@@ -115,6 +123,50 @@ describe("MCP server", () => {
|
||||
expect(invalidated()).toBe(1);
|
||||
});
|
||||
|
||||
it("offers the catalogue resource to read:catalog principals and serves it as JSON", async () => {
|
||||
const { client } = await connect(["read:catalog"]);
|
||||
const { resourceTemplates } = await client.listResourceTemplates();
|
||||
expect(resourceTemplates.map((t) => t.uriTemplate)).toEqual([MODELS_RESOURCE_TEMPLATE]);
|
||||
const { resources } = await client.listResources();
|
||||
expect(resources.map((r) => r.uri).sort()).toEqual([
|
||||
"artcraft://models/audio",
|
||||
"artcraft://models/image",
|
||||
"artcraft://models/mesh",
|
||||
"artcraft://models/splat",
|
||||
"artcraft://models/video",
|
||||
]);
|
||||
const read = await client.readResource({ uri: "artcraft://models/mesh" });
|
||||
const content = read.contents[0];
|
||||
expect(content?.mimeType).toBe("application/json");
|
||||
const text = content && "text" in content ? content.text : "";
|
||||
const parsed = JSON.parse(text) as { kind: string; models: unknown[] };
|
||||
expect(parsed.kind).toBe("mesh");
|
||||
expect(parsed.models.length).toBeGreaterThan(0);
|
||||
await expect(client.readResource({ uri: "artcraft://models/nope" })).rejects.toThrow(
|
||||
/Unknown catalogue/,
|
||||
);
|
||||
});
|
||||
|
||||
it("withholds the catalogue resource without read:catalog", async () => {
|
||||
const { client } = await connect(["read:account"]);
|
||||
expect(client.getServerCapabilities()?.resources).toBeUndefined();
|
||||
});
|
||||
|
||||
it("serves the plan_generation prompt", async () => {
|
||||
const { client } = await connect(["read:account"]);
|
||||
const { prompts } = await client.listPrompts();
|
||||
expect(prompts.map((p) => p.name)).toEqual([PLAN_GENERATION_PROMPT]);
|
||||
const prompt = await client.getPrompt({
|
||||
name: PLAN_GENERATION_PROMPT,
|
||||
arguments: { brief: "a corgi surfing at sunset", kind: "video" },
|
||||
});
|
||||
const text = prompt.messages[0]?.content.type === "text" ? prompt.messages[0].content.text : "";
|
||||
expect(text).toContain('"a corgi surfing at sunset"');
|
||||
expect(text).toContain("The kind of output is video.");
|
||||
expect(text).toMatch(/list_models.*estimate_cost.*get_credit_balance/s);
|
||||
expect(text).toContain("Do not generate anything");
|
||||
});
|
||||
|
||||
it("reports an unavailable upstream as a tool error without notifying", async () => {
|
||||
const { client, invalidated } = await connect(["read:account"], 503);
|
||||
const result = await client.callTool({ name: "get_credit_balance", arguments: {} });
|
||||
|
||||
Reference in new issue
Block a user