@mdeleon23/wardrowbe-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/http.js ADDED
@@ -0,0 +1,138 @@
1
+ import { createServer as createHttpServer } from "node:http";
2
+ import { timingSafeEqual } from "node:crypto";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { createServer, SERVER_NAME, SERVER_VERSION } from "./server.js";
5
+ import { ALLOWED_IMAGE_TYPES, MAX_UPLOAD_BYTES, sharedUploads, UPLOAD_TTL_MS, UploadError, } from "./uploads.js";
6
+ /** Constant-time check of the Bearer token, so the comparison doesn't leak the key by timing. */
7
+ export function isAuthorized(header, apiKey) {
8
+ const match = /^Bearer (.+)$/.exec(header ?? "");
9
+ if (!match)
10
+ return false;
11
+ const given = Buffer.from(match[1]);
12
+ const expected = Buffer.from(apiKey);
13
+ return given.length === expected.length && timingSafeEqual(given, expected);
14
+ }
15
+ function sendJson(res, status, body) {
16
+ res.writeHead(status, { "Content-Type": "application/json" });
17
+ res.end(JSON.stringify(body));
18
+ }
19
+ /** Reads the body, or returns "too-large" if it goes past the limit. The rest is drained so the response can be sent. */
20
+ function readBody(req, limit) {
21
+ return new Promise((resolve, reject) => {
22
+ const chunks = [];
23
+ let size = 0;
24
+ let tooLarge = false;
25
+ req.on("data", (chunk) => {
26
+ size += chunk.length;
27
+ if (size > limit) {
28
+ tooLarge = true;
29
+ return;
30
+ }
31
+ if (!tooLarge)
32
+ chunks.push(chunk);
33
+ });
34
+ req.on("end", () => resolve(tooLarge ? "too-large" : Buffer.concat(chunks)));
35
+ req.on("error", reject);
36
+ });
37
+ }
38
+ /** Keeps just a safe file name: no folders, no control characters, at most 200 characters. */
39
+ function sanitizeFilename(header) {
40
+ const raw = Array.isArray(header) ? header[0] : header;
41
+ let name = raw ?? "";
42
+ try {
43
+ name = decodeURIComponent(name);
44
+ }
45
+ catch {
46
+ // Keep the raw value if it isn't valid percent-encoding.
47
+ }
48
+ name = name
49
+ .split(/[\\/]/)
50
+ .pop()
51
+ .replace(/[\u0000-\u001f\u007f]/g, "")
52
+ .trim()
53
+ .slice(0, 200);
54
+ return name || "photo.jpg";
55
+ }
56
+ /**
57
+ * POST /uploads takes the raw photo bytes (Content-Type image/*, optional X-Filename header) and
58
+ * returns an upload_id. The add_item tool then uses that id, so the photo never passes through the model.
59
+ */
60
+ async function handleUpload(req, res, uploads) {
61
+ const contentType = (req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
62
+ if (!ALLOWED_IMAGE_TYPES.includes(contentType)) {
63
+ sendJson(res, 415, { error: `Send the photo as one of: ${ALLOWED_IMAGE_TYPES.join(", ")}` });
64
+ return;
65
+ }
66
+ const declared = Number(req.headers["content-length"]);
67
+ if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES) {
68
+ sendJson(res, 413, { error: `Photo is larger than ${MAX_UPLOAD_BYTES / 1024 / 1024} MB` });
69
+ return;
70
+ }
71
+ const body = await readBody(req, MAX_UPLOAD_BYTES);
72
+ if (body === "too-large") {
73
+ sendJson(res, 413, { error: `Photo is larger than ${MAX_UPLOAD_BYTES / 1024 / 1024} MB` });
74
+ return;
75
+ }
76
+ if (body.length === 0) {
77
+ sendJson(res, 400, { error: "The request had no photo data" });
78
+ return;
79
+ }
80
+ try {
81
+ const upload_id = uploads.put({
82
+ bytes: body,
83
+ contentType,
84
+ filename: sanitizeFilename(req.headers["x-filename"]),
85
+ });
86
+ sendJson(res, 201, { upload_id, expires_in_seconds: UPLOAD_TTL_MS / 1000 });
87
+ }
88
+ catch (err) {
89
+ if (err instanceof UploadError) {
90
+ sendJson(res, 429, { error: err.message });
91
+ return;
92
+ }
93
+ throw err;
94
+ }
95
+ }
96
+ /**
97
+ * Serves the MCP endpoint at /mcp over Streamable HTTP, stateless, behind a Bearer API key.
98
+ * Also serves POST /uploads, where the app sends a photo before asking the agent to add it.
99
+ */
100
+ export function createMcpHttpServer(config, uploads = sharedUploads) {
101
+ const apiKey = config.apiKey;
102
+ if (!apiKey)
103
+ throw new Error("MCP_API_KEY is required for the http transport");
104
+ return createHttpServer(async (req, res) => {
105
+ const url = new URL(req.url ?? "/", "http://localhost");
106
+ if (url.pathname === "/" && req.method === "GET") {
107
+ sendJson(res, 200, { name: SERVER_NAME, version: SERVER_VERSION, endpoint: "/mcp", uploads: "/uploads" });
108
+ return;
109
+ }
110
+ if (url.pathname !== "/mcp" && url.pathname !== "/uploads") {
111
+ sendJson(res, 404, { error: "not found" });
112
+ return;
113
+ }
114
+ if (!isAuthorized(req.headers.authorization, apiKey)) {
115
+ res.setHeader("WWW-Authenticate", "Bearer");
116
+ sendJson(res, 401, { error: "unauthorized" });
117
+ return;
118
+ }
119
+ if (url.pathname === "/uploads") {
120
+ if (req.method !== "POST") {
121
+ res.setHeader("Allow", "POST");
122
+ sendJson(res, 405, { error: "method not allowed" });
123
+ return;
124
+ }
125
+ await handleUpload(req, res, uploads);
126
+ return;
127
+ }
128
+ // Stateless: a fresh server and transport per request, so no session state is kept between calls.
129
+ const server = createServer(config, fetch, uploads);
130
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
131
+ res.on("close", () => {
132
+ void transport.close();
133
+ void server.close();
134
+ });
135
+ await server.connect(transport);
136
+ await transport.handleRequest(req, res);
137
+ });
138
+ }
@@ -0,0 +1,5 @@
1
+ export { loadConfig, ConfigError, type Config, type Transport } from "./config.js";
2
+ export { WardrowbeClient, TokenProvider, WardrowbeApiError } from "./client.js";
3
+ export { createServer, SERVER_NAME, SERVER_VERSION } from "./server.js";
4
+ export { registerTools } from "./tools.js";
5
+ export { createMcpHttpServer, isAuthorized } from "./http.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { loadConfig, ConfigError } from "./config.js";
2
+ export { WardrowbeClient, TokenProvider, WardrowbeApiError } from "./client.js";
3
+ export { createServer, SERVER_NAME, SERVER_VERSION } from "./server.js";
4
+ export { registerTools } from "./tools.js";
5
+ export { createMcpHttpServer, isAuthorized } from "./http.js";
@@ -0,0 +1,32 @@
1
+ export interface Pkce {
2
+ verifier: string;
3
+ challenge: string;
4
+ }
5
+ /** Creates a PKCE verifier and its S256 challenge (RFC 7636). */
6
+ export declare function createPkce(): Pkce;
7
+ /** S256 code challenge for a verifier. */
8
+ export declare function challengeFor(verifier: string): string;
9
+ export interface LoginOptions {
10
+ issuerUrl: string;
11
+ clientId: string;
12
+ clientSecret?: string;
13
+ port: number;
14
+ fetchFn?: typeof fetch;
15
+ /** Opens the authorize URL. Defaults to the platform browser opener. Failures are ignored. */
16
+ openBrowser?: (url: string) => void;
17
+ /** Receives human-readable progress. Defaults to stderr. */
18
+ log?: (message: string) => void;
19
+ /** How long to wait for the browser sign-in to come back. */
20
+ timeoutMs?: number;
21
+ }
22
+ export interface LoginResult {
23
+ refreshToken: string;
24
+ idToken?: string;
25
+ }
26
+ /** Localhost port for the sign-in redirect. Register `http://localhost:8765/callback` with the IdP. */
27
+ export declare const DEFAULT_LOGIN_PORT = 8765;
28
+ /**
29
+ * Runs the one-time sign-in: opens the browser at the issuer's authorize endpoint with PKCE and
30
+ * `offline_access`, catches the redirect on localhost, and exchanges the code for a refresh token.
31
+ */
32
+ export declare function runLogin(opts: LoginOptions): Promise<LoginResult>;
package/dist/login.js ADDED
@@ -0,0 +1,140 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { spawn } from "node:child_process";
4
+ /** Creates a PKCE verifier and its S256 challenge (RFC 7636). */
5
+ export function createPkce() {
6
+ const verifier = randomBytes(32).toString("base64url");
7
+ return { verifier, challenge: challengeFor(verifier) };
8
+ }
9
+ /** S256 code challenge for a verifier. */
10
+ export function challengeFor(verifier) {
11
+ return createHash("sha256").update(verifier).digest("base64url");
12
+ }
13
+ const CALLBACK_PATH = "/callback";
14
+ const DEFAULT_TIMEOUT_MS = 5 * 60_000;
15
+ /** Localhost port for the sign-in redirect. Register `http://localhost:8765/callback` with the IdP. */
16
+ export const DEFAULT_LOGIN_PORT = 8765;
17
+ /**
18
+ * Runs the one-time sign-in: opens the browser at the issuer's authorize endpoint with PKCE and
19
+ * `offline_access`, catches the redirect on localhost, and exchanges the code for a refresh token.
20
+ */
21
+ export async function runLogin(opts) {
22
+ const fetchFn = opts.fetchFn ?? fetch;
23
+ const log = opts.log ?? ((m) => console.error(m));
24
+ const issuer = opts.issuerUrl.replace(/\/+$/, "");
25
+ const discovery = await fetchFn(`${issuer}/.well-known/openid-configuration`, {
26
+ headers: { Accept: "application/json" },
27
+ });
28
+ const meta = (await discovery.json().catch(() => undefined));
29
+ if (!discovery.ok || !meta?.authorization_endpoint || !meta.token_endpoint) {
30
+ throw new Error(`OIDC discovery failed at ${issuer} (HTTP ${discovery.status})`);
31
+ }
32
+ const { verifier, challenge } = createPkce();
33
+ const state = randomBytes(16).toString("base64url");
34
+ const redirectUri = `http://localhost:${opts.port}${CALLBACK_PATH}`;
35
+ const authorizeUrl = new URL(meta.authorization_endpoint);
36
+ authorizeUrl.search = new URLSearchParams({
37
+ response_type: "code",
38
+ client_id: opts.clientId,
39
+ redirect_uri: redirectUri,
40
+ scope: "openid profile email offline_access",
41
+ code_challenge: challenge,
42
+ code_challenge_method: "S256",
43
+ state,
44
+ }).toString();
45
+ const code = await waitForCode({
46
+ port: opts.port,
47
+ state,
48
+ timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
49
+ onListening: () => {
50
+ log(`Sign in with your identity provider. If no browser opens, visit:\n ${authorizeUrl}`);
51
+ (opts.openBrowser ?? openInBrowser)(authorizeUrl.toString());
52
+ },
53
+ });
54
+ const form = new URLSearchParams({
55
+ grant_type: "authorization_code",
56
+ code,
57
+ redirect_uri: redirectUri,
58
+ client_id: opts.clientId,
59
+ code_verifier: verifier,
60
+ });
61
+ if (opts.clientSecret)
62
+ form.set("client_secret", opts.clientSecret);
63
+ const res = await fetchFn(meta.token_endpoint, {
64
+ method: "POST",
65
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
66
+ body: form,
67
+ });
68
+ const tokens = (await res.json().catch(() => undefined));
69
+ if (!res.ok || !tokens) {
70
+ throw new Error(`Token exchange failed (HTTP ${res.status}${tokens?.error ? `: ${tokens.error}` : ""})`);
71
+ }
72
+ if (!tokens.refresh_token) {
73
+ throw new Error("The identity provider returned no refresh_token. Allow the offline_access scope for this client and sign in again.");
74
+ }
75
+ return { refreshToken: tokens.refresh_token, idToken: tokens.id_token };
76
+ }
77
+ /** Starts a localhost listener and resolves with the authorization code from the redirect. */
78
+ function waitForCode(opts) {
79
+ return new Promise((resolve, reject) => {
80
+ let server;
81
+ const timer = setTimeout(() => {
82
+ server?.close();
83
+ reject(new Error("Timed out waiting for the browser sign-in"));
84
+ }, opts.timeoutMs);
85
+ server = createServer((req, res) => {
86
+ const url = new URL(req.url ?? "/", "http://localhost");
87
+ if (url.pathname !== CALLBACK_PATH) {
88
+ res.writeHead(404).end("not found");
89
+ return;
90
+ }
91
+ const error = url.searchParams.get("error");
92
+ const code = url.searchParams.get("code");
93
+ const state = url.searchParams.get("state");
94
+ if (error) {
95
+ res.writeHead(400, { "Content-Type": "text/plain" }).end(`Sign-in failed: ${error}`);
96
+ finish(new Error(`Sign-in failed: ${error}`));
97
+ return;
98
+ }
99
+ if (!code || state !== opts.state) {
100
+ res.writeHead(400, { "Content-Type": "text/plain" }).end("Invalid sign-in response");
101
+ finish(new Error("Sign-in response had a missing code or a mismatched state"));
102
+ return;
103
+ }
104
+ res
105
+ .writeHead(200, { "Content-Type": "text/html" })
106
+ .end("<h1>Signed in</h1><p>You can close this tab and return to the terminal.</p>");
107
+ finish(undefined, code);
108
+ });
109
+ function finish(err, code) {
110
+ clearTimeout(timer);
111
+ server?.close();
112
+ if (err)
113
+ reject(err);
114
+ else
115
+ resolve(code);
116
+ }
117
+ server.on("error", (err) => {
118
+ clearTimeout(timer);
119
+ reject(err);
120
+ });
121
+ server.listen(opts.port, "127.0.0.1", () => opts.onListening());
122
+ });
123
+ }
124
+ /** Opens a URL in the default browser without blocking. Errors are ignored; the URL is printed too. */
125
+ function openInBrowser(url) {
126
+ const command = process.platform === "darwin"
127
+ ? "open"
128
+ : process.platform === "win32"
129
+ ? "cmd"
130
+ : "xdg-open";
131
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
132
+ try {
133
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
134
+ child.on("error", () => { });
135
+ child.unref();
136
+ }
137
+ catch {
138
+ // The URL is already printed for the user to open by hand.
139
+ }
140
+ }
@@ -0,0 +1,7 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Config } from "./config.js";
3
+ import { type UploadStore } from "./uploads.js";
4
+ export declare const SERVER_NAME = "wardrowbe-mcp";
5
+ export declare const SERVER_VERSION = "0.2.0";
6
+ /** Builds an MCP server with all Wardrowbe tools registered against the configured instance. */
7
+ export declare function createServer(config: Config, fetchFn?: typeof fetch, uploads?: UploadStore): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,59 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { WardrowbeClient, TokenProvider } from "./client.js";
4
+ import { DEFAULT_LOGIN_PORT, runLogin } from "./login.js";
5
+ import { registerTools } from "./tools.js";
6
+ import { TokenStore } from "./token-store.js";
7
+ import { sharedUploads } from "./uploads.js";
8
+ export const SERVER_NAME = "wardrowbe-mcp";
9
+ export const SERVER_VERSION = "0.2.0";
10
+ /**
11
+ * Module-level, because the HTTP transport builds a server per request. Only one browser sign-in
12
+ * runs at a time: concurrent callers share it, since the callback port can be bound only once.
13
+ */
14
+ let pendingSignIn;
15
+ /**
16
+ * Sign-in for the OIDC path: the stored refresh token, and a browser sign-in when there is none.
17
+ * The browser sign-in only runs on the first tool call that needs it, not at startup.
18
+ */
19
+ function signInHooks(config) {
20
+ if (!config.oidc)
21
+ return {};
22
+ const oidc = config.oidc;
23
+ return {
24
+ store: config.tokenFile ? new TokenStore(config.tokenFile) : undefined,
25
+ signIn: () => {
26
+ pendingSignIn ??= runLogin({
27
+ issuerUrl: oidc.issuerUrl,
28
+ clientId: oidc.clientId,
29
+ clientSecret: oidc.clientSecret,
30
+ port: DEFAULT_LOGIN_PORT,
31
+ })
32
+ .then((result) => result.refreshToken)
33
+ .finally(() => {
34
+ pendingSignIn = undefined;
35
+ });
36
+ return pendingSignIn;
37
+ },
38
+ };
39
+ }
40
+ /** Agent guidance, shipped in the package. Works from src/ (tests) and dist/ (published build). */
41
+ const SKILL_URI = "skill://wardrowbe-skill/SKILL.md";
42
+ const skillText = readFileSync(new URL("../skill/SKILL.md", import.meta.url), "utf8");
43
+ /** Exposes SKILL.md as an MCP resource, so clients that install skills pick it up. */
44
+ function registerSkill(server) {
45
+ server.registerResource("wardrowbe-skill", SKILL_URI, {
46
+ title: "Wardrowbe skill",
47
+ description: "How to use the Wardrowbe tools: choosing a tool, adding items from photos, archiving.",
48
+ mimeType: "text/markdown",
49
+ }, (uri) => ({ contents: [{ uri: uri.toString(), mimeType: "text/markdown", text: skillText }] }));
50
+ }
51
+ /** Builds an MCP server with all Wardrowbe tools registered against the configured instance. */
52
+ export function createServer(config, fetchFn = fetch, uploads = sharedUploads) {
53
+ const tokens = new TokenProvider(config, fetchFn, Date.now, signInHooks(config));
54
+ const client = new WardrowbeClient(config, tokens, fetchFn);
55
+ const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
56
+ registerTools(server, client, uploads);
57
+ registerSkill(server);
58
+ return server;
59
+ }
@@ -0,0 +1,20 @@
1
+ /** What the server keeps between runs so it doesn't have to sign in again. */
2
+ export interface StoredRefreshToken {
3
+ issuerUrl: string;
4
+ clientId: string;
5
+ refreshToken: string;
6
+ }
7
+ /** Default location: $XDG_CONFIG_HOME/wardrowbe-mcp/refresh-token.json, or ~/.config/... */
8
+ export declare function defaultTokenFile(env: NodeJS.ProcessEnv): string;
9
+ /**
10
+ * Persists the OIDC refresh token to a file readable only by the current user. Entries are keyed
11
+ * by issuer and client ID, so a changed config never reuses a token from another IdP.
12
+ */
13
+ export declare class TokenStore {
14
+ readonly path: string;
15
+ constructor(path: string);
16
+ /** Returns the stored refresh token for this issuer and client, or undefined if there is none. */
17
+ load(issuerUrl: string, clientId: string): Promise<string | undefined>;
18
+ /** Writes the token atomically: a temp file is renamed over the old one, so a crash never leaves a partial file. */
19
+ save(entry: StoredRefreshToken): Promise<void>;
20
+ }
@@ -0,0 +1,49 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ /** Default location: $XDG_CONFIG_HOME/wardrowbe-mcp/refresh-token.json, or ~/.config/... */
5
+ export function defaultTokenFile(env) {
6
+ const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config");
7
+ return join(base, "wardrowbe-mcp", "refresh-token.json");
8
+ }
9
+ /**
10
+ * Persists the OIDC refresh token to a file readable only by the current user. Entries are keyed
11
+ * by issuer and client ID, so a changed config never reuses a token from another IdP.
12
+ */
13
+ export class TokenStore {
14
+ path;
15
+ constructor(path) {
16
+ this.path = path;
17
+ }
18
+ /** Returns the stored refresh token for this issuer and client, or undefined if there is none. */
19
+ async load(issuerUrl, clientId) {
20
+ let raw;
21
+ try {
22
+ raw = await readFile(this.path, "utf8");
23
+ }
24
+ catch (err) {
25
+ if (err.code === "ENOENT")
26
+ return undefined;
27
+ throw err;
28
+ }
29
+ let entry;
30
+ try {
31
+ entry = JSON.parse(raw);
32
+ }
33
+ catch {
34
+ // A corrupt file is treated as missing; the next sign-in overwrites it.
35
+ return undefined;
36
+ }
37
+ if (entry.issuerUrl !== issuerUrl || entry.clientId !== clientId || !entry.refreshToken) {
38
+ return undefined;
39
+ }
40
+ return entry.refreshToken;
41
+ }
42
+ /** Writes the token atomically: a temp file is renamed over the old one, so a crash never leaves a partial file. */
43
+ async save(entry) {
44
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
45
+ const tmp = `${this.path}.tmp`;
46
+ await writeFile(tmp, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600 });
47
+ await rename(tmp, this.path);
48
+ }
49
+ }
@@ -0,0 +1,5 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { WardrowbeClient } from "./client.js";
3
+ import { type UploadStore } from "./uploads.js";
4
+ /** Registers the Wardrowbe tools on an MCP server. */
5
+ export declare function registerTools(server: McpServer, client: WardrowbeClient, uploads?: UploadStore): void;
package/dist/tools.js ADDED
@@ -0,0 +1,183 @@
1
+ import { z } from "zod";
2
+ import { ALLOWED_IMAGE_TYPES, MAX_TOOL_UPLOAD_BYTES, sharedUploads, } from "./uploads.js";
3
+ const uuid = z.string().uuid().describe("Item or outfit UUID");
4
+ const isoDate = z
5
+ .string()
6
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Use YYYY-MM-DD")
7
+ .describe("Date as YYYY-MM-DD");
8
+ /** Wraps a tool body so API errors come back as tool errors the model can read, not crashes. */
9
+ async function run(fn) {
10
+ try {
11
+ const result = await fn();
12
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
13
+ }
14
+ catch (err) {
15
+ const message = err instanceof Error ? err.message : String(err);
16
+ return { content: [{ type: "text", text: message }], isError: true };
17
+ }
18
+ }
19
+ /** Registers the Wardrowbe tools on an MCP server. */
20
+ export function registerTools(server, client, uploads = sharedUploads) {
21
+ server.registerTool("list_items", {
22
+ title: "List wardrobe items",
23
+ description: "List items in the user's wardrobe. Filter by type, status, favorites, or items that need washing.",
24
+ inputSchema: {
25
+ type: z.string().optional().describe("Item type, e.g. top, bottom, shoes"),
26
+ subtype: z.string().optional(),
27
+ colors: z.string().optional().describe("Comma-separated color names"),
28
+ status: z.string().optional(),
29
+ favorite: z.boolean().optional(),
30
+ needs_wash: z.boolean().optional(),
31
+ search: z.string().optional(),
32
+ page: z.number().int().min(1).optional(),
33
+ page_size: z.number().int().min(1).optional(),
34
+ },
35
+ }, (args) => run(() => client.get("/items", args)));
36
+ server.registerTool("get_item", {
37
+ title: "Get a wardrobe item",
38
+ description: "Get full details for one wardrobe item, including its wear and wash status.",
39
+ inputSchema: { item_id: uuid },
40
+ }, ({ item_id }) => run(() => client.get(`/items/${item_id}`)));
41
+ server.registerTool("log_wear", {
42
+ title: "Log an item as worn",
43
+ description: "Record that an item was worn. Defaults to today in the user's timezone when worn_at is omitted.",
44
+ inputSchema: {
45
+ item_id: uuid,
46
+ worn_at: isoDate.optional(),
47
+ occasion: z.string().optional(),
48
+ notes: z.string().optional(),
49
+ },
50
+ }, ({ item_id, ...body }) => run(() => client.post(`/items/${item_id}/wear`, body)));
51
+ server.registerTool("log_wash", {
52
+ title: "Log an item as washed",
53
+ description: "Record that an item was washed. Defaults to today in the user's timezone when washed_at is omitted.",
54
+ inputSchema: {
55
+ item_id: uuid,
56
+ washed_at: isoDate.optional(),
57
+ method: z.string().max(50).optional(),
58
+ notes: z.string().optional(),
59
+ },
60
+ }, ({ item_id, ...body }) => run(() => client.post(`/items/${item_id}/wash`, body)));
61
+ server.registerTool("suggest_outfit", {
62
+ title: "Suggest an outfit",
63
+ description: "Ask Wardrowbe to suggest an outfit from the wardrobe. Rate limited to about 10 requests per minute per user.",
64
+ inputSchema: {
65
+ occasion: z.string().optional(),
66
+ time_of_day: z.string().optional(),
67
+ exclude_items: z.array(uuid).optional(),
68
+ include_items: z.array(uuid).optional(),
69
+ },
70
+ }, (args) => run(() => client.post("/outfits/suggest", {
71
+ occasion: args.occasion,
72
+ time_of_day: args.time_of_day,
73
+ exclude_items: args.exclude_items ?? [],
74
+ include_items: args.include_items ?? [],
75
+ })));
76
+ server.registerTool("accept_outfit", {
77
+ title: "Accept an outfit",
78
+ description: "Mark a suggested outfit as accepted.",
79
+ inputSchema: { outfit_id: uuid },
80
+ }, ({ outfit_id }) => run(() => client.post(`/outfits/${outfit_id}/accept`)));
81
+ server.registerTool("reject_outfit", {
82
+ title: "Reject an outfit",
83
+ description: "Mark a suggested outfit as rejected, so it is not suggested again.",
84
+ inputSchema: { outfit_id: uuid },
85
+ }, ({ outfit_id }) => run(() => client.post(`/outfits/${outfit_id}/reject`)));
86
+ server.registerTool("get_analytics", {
87
+ title: "Wardrobe analytics",
88
+ description: "Get wardrobe analytics, including trends over a chosen window of days.",
89
+ inputSchema: {
90
+ days: z.number().int().min(7).max(365).optional().describe("Trend window, 7 to 365 days"),
91
+ },
92
+ }, ({ days }) => run(() => client.get("/analytics", { days: days ?? 30 })));
93
+ server.registerTool("upload_photo", {
94
+ title: "Upload a photo",
95
+ description: `Upload a photo of a clothing item so add_item can use it. Pass the image as base64. Keep it small: the limit is ${MAX_TOOL_UPLOAD_BYTES / 1024} KB, so use a reduced-size image. Returns an upload_id for add_item. The id is good for 10 minutes and works once.`,
96
+ inputSchema: {
97
+ image_base64: z.string().min(1).describe("The image bytes, base64-encoded, without a data: prefix"),
98
+ mime_type: z.enum(ALLOWED_IMAGE_TYPES).describe("Image type"),
99
+ filename: z.string().max(200).optional().describe("File name, e.g. blue-shirt.jpg"),
100
+ },
101
+ }, ({ image_base64, mime_type, filename }) => run(async () => {
102
+ const bytes = Buffer.from(image_base64, "base64");
103
+ if (bytes.length === 0)
104
+ throw new Error("The image_base64 value decoded to no data.");
105
+ if (bytes.length > MAX_TOOL_UPLOAD_BYTES) {
106
+ throw new Error(`The photo is ${Math.round(bytes.length / 1024)} KB, over the ${MAX_TOOL_UPLOAD_BYTES / 1024} KB limit for upload_photo. Send a smaller image.`);
107
+ }
108
+ const upload_id = uploads.put({ bytes, contentType: mime_type, filename: filename ?? "photo.jpg" });
109
+ return { upload_id, expires_in_seconds: 600 };
110
+ }));
111
+ server.registerTool("add_item", {
112
+ title: "Add a wardrobe item",
113
+ description: "Add a new item to the wardrobe from a photo. The photo must first be uploaded to the server's upload endpoint, which returns an upload_id. Pass that id here. Wardrowbe detects the type and colors unless skip_ai is true or you pass them.",
114
+ inputSchema: {
115
+ upload_id: z.string().uuid().describe("upload_id returned when the photo was uploaded"),
116
+ type: z.string().optional().describe("Item type, e.g. top, bottom, shoes. Detected if omitted."),
117
+ subtype: z.string().optional(),
118
+ name: z.string().max(100).optional(),
119
+ brand: z.string().max(100).optional(),
120
+ notes: z.string().max(1000).optional(),
121
+ colors: z.string().optional().describe("Comma-separated color names"),
122
+ primary_color: z.string().optional(),
123
+ favorite: z.boolean().optional(),
124
+ skip_ai: z.boolean().optional().describe("Skip AI tagging and use only the fields given"),
125
+ },
126
+ }, ({ upload_id, ...fields }) => run(async () => {
127
+ const photo = uploads.take(upload_id);
128
+ const form = new FormData();
129
+ const bytes = new Uint8Array(photo.bytes);
130
+ form.append("image", new Blob([bytes], { type: photo.contentType }), photo.filename);
131
+ for (const [key, value] of Object.entries(fields)) {
132
+ if (value !== undefined)
133
+ form.append(key, String(value));
134
+ }
135
+ return client.postForm("/items", form);
136
+ }));
137
+ server.registerTool("get_wardrobe_summary", {
138
+ title: "Wardrobe summary",
139
+ description: "A short overview of the wardrobe: item counts, the insights Wardrowbe has noticed, and the most and least worn items. Good first call when a user asks how their wardrobe is doing.",
140
+ inputSchema: {
141
+ days: z.number().int().min(7).max(365).optional().describe("Trend window, 7 to 365 days"),
142
+ },
143
+ }, ({ days }) => run(async () => {
144
+ const analytics = await client.get("/analytics", { days: days ?? 30 });
145
+ return {
146
+ wardrobe: analytics.wardrobe,
147
+ insights: analytics.insights,
148
+ most_worn: analytics.most_worn,
149
+ never_worn: analytics.never_worn,
150
+ };
151
+ }));
152
+ server.registerTool("get_most_worn_items", {
153
+ title: "Most worn items",
154
+ description: "The items worn most often in the trend window. Wardrowbe returns at most 5.",
155
+ inputSchema: {
156
+ limit: z.number().int().min(1).max(5).optional().describe("How many items, up to 5"),
157
+ days: z.number().int().min(7).max(365).optional().describe("Trend window, 7 to 365 days"),
158
+ },
159
+ }, ({ limit, days }) => run(async () => {
160
+ const analytics = await client.get("/analytics", { days: days ?? 30 });
161
+ return { items: analytics.most_worn.slice(0, limit ?? 5) };
162
+ }));
163
+ server.registerTool("get_items_to_wash", {
164
+ title: "Items to wash",
165
+ description: "Items worn since their last wash, so they are due for washing.",
166
+ inputSchema: {
167
+ limit: z.number().int().min(1).max(100).optional().describe("How many items to return"),
168
+ },
169
+ }, ({ limit }) => run(() => client.get("/items", { needs_wash: true, page_size: limit ?? 20 })));
170
+ server.registerTool("archive_item", {
171
+ title: "Archive an item",
172
+ description: "Archive an item so it is left out of outfit suggestions. It stays in the wardrobe and can be restored. Use this for items that are worn out, given away, or out of season.",
173
+ inputSchema: {
174
+ item_id: uuid,
175
+ reason: z.string().max(200).optional().describe("Why the item is archived, e.g. worn out"),
176
+ },
177
+ }, ({ item_id, reason }) => run(() => client.post(`/items/${item_id}/archive`, reason === undefined ? {} : { reason })));
178
+ server.registerTool("restore_item", {
179
+ title: "Restore an archived item",
180
+ description: "Bring an archived item back into the active wardrobe and outfit suggestions.",
181
+ inputSchema: { item_id: uuid },
182
+ }, ({ item_id }) => run(() => client.post(`/items/${item_id}/restore`)));
183
+ }