@sketric/favstash-mcp 0.3.0 → 0.4.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.
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { realpathSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+ import { PACKAGE, endpoint } from "./config.js";
6
+ import { login, logout, authStatus } from "./auth.js";
7
+ import { setupAgent } from "./setup.js";
8
+ import { contracts, localTools } from "./contracts.js";
9
+ import { remoteClient } from "./remote.js";
10
+ import {
11
+ CallToolResultSchema,
12
+ InitializeResultSchema,
13
+ ListToolsResultSchema,
14
+ } from "@modelcontextprotocol/sdk/types.js";
15
+
16
+ const HELP = `FavStash CLI ${PACKAGE.version}
17
+
18
+ Connect a local coding agent to FavStash with browser sign-in and local files.
19
+
20
+ favstash auth login [--no-browser] [--credential-store keychain|file]
21
+ favstash auth status
22
+ favstash auth logout [--local-only]
23
+ favstash setup --agent codex|claude-code [--dry-run]
24
+ favstash doctor
25
+ favstash mcp Start the stdio MCP bridge
26
+ favstash tools Print the bundled tool catalogue as JSON
27
+ favstash --version
28
+
29
+ Results are JSON on stdout. Login instructions and errors use stderr.
30
+ OAuth uses your OS credential store. File storage is an explicit fallback.
31
+ FAVSTASH_API_KEY overrides OAuth for automation; never paste its value in chat.
32
+ FAVSTASH_MCP_URL selects a different trusted environment.
33
+ Docs: https://www.favstash.app/cli
34
+ `;
35
+
36
+ function canonical(value) {
37
+ if (Array.isArray(value)) return value.map(canonical);
38
+ if (value && typeof value === "object")
39
+ return Object.fromEntries(
40
+ Object.keys(value)
41
+ .sort()
42
+ .map((key) => [key, canonical(value[key])]),
43
+ );
44
+ return value;
45
+ }
46
+
47
+ export async function doctor(remote = remoteClient()) {
48
+ const server = InitializeResultSchema.parse(
49
+ await remote.rpc("initialize", {
50
+ protocolVersion: "2025-11-25",
51
+ capabilities: {},
52
+ clientInfo: { name: "favstash-cli-doctor", version: PACKAGE.version },
53
+ }),
54
+ );
55
+ if (!["2025-11-25", "2025-06-18"].includes(server.protocolVersion))
56
+ throw new Error(
57
+ `FavStash negotiated unsupported MCP protocol ${server.protocolVersion}. Update the CLI or report a server compatibility problem.`,
58
+ );
59
+ await remote.notify("notifications/initialized");
60
+ const discovered = ListToolsResultSchema.parse(
61
+ await remote.rpc("tools/list"),
62
+ );
63
+ const changed = contracts.tools
64
+ .filter((expected) => {
65
+ const actual = discovered.tools?.find(
66
+ (tool) => tool.name === expected.name,
67
+ );
68
+ return (
69
+ !actual ||
70
+ JSON.stringify(canonical(actual.inputSchema)) !==
71
+ JSON.stringify(canonical(expected.inputSchema))
72
+ );
73
+ })
74
+ .map((tool) => tool.name);
75
+ let readVerified = false;
76
+ if (changed.length === 0) {
77
+ const summary = discovered.tools.find(
78
+ (tool) => tool.name === "get_stash_summary",
79
+ );
80
+ if (summary?.annotations?.readOnlyHint !== true)
81
+ throw new Error(
82
+ "FavStash did not advertise a read-only get_stash_summary tool. No tool was called.",
83
+ );
84
+ const result = CallToolResultSchema.parse(
85
+ await remote.rpc("tools/call", {
86
+ name: "get_stash_summary",
87
+ arguments: {},
88
+ }),
89
+ );
90
+ readVerified = result.isError !== true;
91
+ if (!readVerified)
92
+ throw new Error(
93
+ "FavStash initialization and discovery succeeded, but get_stash_summary returned a tool error. Account access is not verified; inspect the host's tool result before retrying.",
94
+ );
95
+ }
96
+ return {
97
+ ready: changed.length === 0,
98
+ version: PACKAGE.version,
99
+ contractHash: contracts.contractHash,
100
+ server: server.serverInfo,
101
+ toolCount: discovered.tools?.length || 0,
102
+ incompatibleTools: changed,
103
+ readOnlyCheck: { tool: "get_stash_summary", success: readVerified },
104
+ verification: changed.length
105
+ ? "Initialization completed; hosted tool schemas are incompatible. No tool was called."
106
+ : "Authenticated initialization, initialized notification, tool discovery, and one count-only read succeeded. No content changed.",
107
+ ...(changed.length
108
+ ? {
109
+ next: "Update with npm install -g @sketric/favstash-mcp@latest, restart your host, and run doctor again.",
110
+ }
111
+ : {}),
112
+ };
113
+ }
114
+
115
+ export async function main(argv = process.argv.slice(2)) {
116
+ const { values, positionals } = parseArgs({
117
+ args: argv,
118
+ allowPositionals: true,
119
+ options: {
120
+ help: { type: "boolean", short: "h" },
121
+ version: { type: "boolean", short: "v" },
122
+ "no-browser": { type: "boolean" },
123
+ "credential-store": { type: "string" },
124
+ "local-only": { type: "boolean" },
125
+ agent: { type: "string" },
126
+ "dry-run": { type: "boolean" },
127
+ },
128
+ });
129
+ if (values.help || (!positionals.length && !values.version)) {
130
+ console.log(HELP);
131
+ return;
132
+ }
133
+ if (values.version) {
134
+ console.log(PACKAGE.version);
135
+ return;
136
+ }
137
+ let result;
138
+ const command = positionals.join(" ");
139
+ if (command === "mcp") {
140
+ const { startBridge } = await import("./bridge.js");
141
+ await startBridge();
142
+ return;
143
+ }
144
+ if (command === "auth login")
145
+ result = await login({
146
+ storage: values["credential-store"] || "keychain",
147
+ noBrowser: values["no-browser"],
148
+ });
149
+ else if (command === "auth status") result = await authStatus();
150
+ else if (command === "auth logout")
151
+ result = await logout({ localOnly: values["local-only"] });
152
+ else if (command === "setup")
153
+ result = await setupAgent(values.agent, { dryRun: values["dry-run"] });
154
+ else if (command === "doctor") {
155
+ result = await doctor();
156
+ if (!result.ready) process.exitCode = 2;
157
+ } else if (command === "tools")
158
+ result = {
159
+ version: PACKAGE.version,
160
+ endpoint: endpoint(),
161
+ tools: localTools,
162
+ };
163
+ else throw new Error(`Unknown command: ${command}. Run favstash --help.`);
164
+ console.log(JSON.stringify(result, null, 2));
165
+ }
166
+
167
+ if (
168
+ process.argv[1] &&
169
+ fileURLToPath(import.meta.url) === realpathSync(process.argv[1])
170
+ ) {
171
+ main().catch((error) => {
172
+ console.error(JSON.stringify({ error: error.message }));
173
+ process.exitCode = 1;
174
+ });
175
+ }
@@ -19,6 +19,7 @@ const FILE_TYPES = new Map([
19
19
  [".jpeg", { contentType: "image/jpeg", type: "image" }],
20
20
  [".png", { contentType: "image/png", type: "image" }],
21
21
  [".webp", { contentType: "image/webp", type: "image" }],
22
+ [".gif", { contentType: "image/gif", type: "image" }],
22
23
  [".mp4", { contentType: "video/mp4", type: "video" }],
23
24
  [".mov", { contentType: "video/quicktime", type: "video" }],
24
25
  [".pdf", { contentType: "application/pdf", type: "document" }],
@@ -126,6 +127,9 @@ function matchesMagicBytes(contentType, head) {
126
127
  head.subarray(8, 12).toString("ascii") === "WEBP"
127
128
  );
128
129
  }
130
+ if (contentType === "image/gif") {
131
+ return ["GIF87a", "GIF89a"].includes(head.subarray(0, 6).toString("ascii"));
132
+ }
129
133
  if (contentType === "application/pdf") {
130
134
  return head.subarray(0, 5).toString("ascii") === "%PDF-";
131
135
  }
@@ -191,7 +195,7 @@ export async function validateLocalMediaFile(filePath, role = "media") {
191
195
  const type = FILE_TYPES.get(extension);
192
196
  if (!type) {
193
197
  throw new Error(
194
- `Unsupported local ${label} extension "${extension || "(none)"}". Use JPEG, PNG, WebP, MP4, MOV, or PDF.`,
198
+ `Unsupported local ${label} extension "${extension || "(none)"}". Use JPEG, PNG, WebP, GIF, MP4, MOV, or PDF.`,
195
199
  );
196
200
  }
197
201
  if (
@@ -359,25 +363,29 @@ async function runWithConcurrency(count, concurrency, worker) {
359
363
 
360
364
  export function createLocalMediaUploadClient({
361
365
  apiKey,
366
+ authorizedFetch,
362
367
  apiBaseUrl,
363
368
  fetchImpl = fetch,
364
369
  timeoutMs = DEFAULT_UPLOAD_TIMEOUT_MS,
365
370
  }) {
366
- if (!apiKey)
371
+ if (!apiKey && !authorizedFetch)
367
372
  throw new Error("FavStash API credential is required for uploads.");
368
373
  const baseUrl = apiBaseUrl.replace(/\/+$/, "");
369
374
 
370
375
  async function postJson(route, body, label) {
371
- const response = await fetchImpl(`${baseUrl}${route}`, {
372
- method: "POST",
373
- headers: {
374
- Authorization: `Bearer ${apiKey}`,
375
- "Content-Type": "application/json",
376
- Accept: "application/json",
376
+ const response = await (authorizedFetch ?? fetchImpl)(
377
+ `${baseUrl}${route}`,
378
+ {
379
+ method: "POST",
380
+ headers: {
381
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
382
+ "Content-Type": "application/json",
383
+ Accept: "application/json",
384
+ },
385
+ body: JSON.stringify(body),
386
+ signal: uploadSignal(timeoutMs),
377
387
  },
378
- body: JSON.stringify(body),
379
- signal: uploadSignal(timeoutMs),
380
- });
388
+ );
381
389
  return readJsonResponse(response, label);
382
390
  }
383
391
 
package/bin/remote.js ADDED
@@ -0,0 +1,94 @@
1
+ import { accessToken } from "./auth.js";
2
+ import { endpoint } from "./config.js";
3
+
4
+ export function remoteClient({
5
+ url = endpoint(),
6
+ fetchImpl = fetch,
7
+ getToken = (rejectedToken) => accessToken({ url, fetchImpl, rejectedToken }),
8
+ } = {}) {
9
+ let nextId = 1;
10
+ let protocolVersion;
11
+ let sessionId;
12
+ async function authorizedFetch(input, init = {}) {
13
+ if (new URL(input).origin !== new URL(url).origin)
14
+ throw new Error(
15
+ "Refusing to send FavStash credentials to another origin.",
16
+ );
17
+ let token = await getToken();
18
+ const request = () =>
19
+ fetchImpl(input, {
20
+ ...init,
21
+ redirect: "error",
22
+ headers: { ...init.headers, Authorization: `Bearer ${token}` },
23
+ signal: init.signal || AbortSignal.timeout(60_000),
24
+ });
25
+ let response = await request();
26
+ if (response.status === 401 && !process.env.FAVSTASH_API_KEY) {
27
+ await response.body?.cancel();
28
+ token = await getToken(token);
29
+ response = await request();
30
+ }
31
+ return response;
32
+ }
33
+ async function post(message) {
34
+ const response = await authorizedFetch(url, {
35
+ method: "POST",
36
+ headers: {
37
+ "Content-Type": "application/json",
38
+ Accept: "application/json, text/event-stream",
39
+ ...(protocolVersion ? { "MCP-Protocol-Version": protocolVersion } : {}),
40
+ ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
41
+ },
42
+ body: JSON.stringify(message),
43
+ });
44
+ if (response.status === 401)
45
+ throw new Error(
46
+ "FavStash rejected the credential. Run favstash auth login again, or check FAVSTASH_API_KEY.",
47
+ );
48
+ if (!response.ok)
49
+ throw new Error(
50
+ `FavStash returned HTTP ${response.status}. Retry reads after transient failures; inspect post state before retrying a write.`,
51
+ );
52
+ return response;
53
+ }
54
+ return {
55
+ authorizedFetch,
56
+ async rpc(method, params = {}) {
57
+ const id = nextId++;
58
+ const response = await post({ jsonrpc: "2.0", id, method, params });
59
+ const data = await response.json().catch(() => {
60
+ throw new Error("FavStash returned an invalid JSON-RPC response.");
61
+ });
62
+ if (
63
+ !data ||
64
+ data.jsonrpc !== "2.0" ||
65
+ data.id !== id ||
66
+ Object.hasOwn(data, "result") === Object.hasOwn(data, "error")
67
+ )
68
+ throw new Error(
69
+ "FavStash returned an invalid JSON-RPC response or request ID.",
70
+ );
71
+ if (data.error)
72
+ throw new Error(data.error.message || "FavStash MCP request failed.");
73
+ if (
74
+ !data.result ||
75
+ typeof data.result !== "object" ||
76
+ Array.isArray(data.result)
77
+ )
78
+ throw new Error("FavStash returned an invalid MCP response.");
79
+ if (method === "initialize") {
80
+ protocolVersion = data.result.protocolVersion;
81
+ sessionId = response.headers.get("mcp-session-id");
82
+ }
83
+ return data.result;
84
+ },
85
+ async notify(method, params = {}) {
86
+ const response = await post({ jsonrpc: "2.0", method, params });
87
+ const body = await response.text();
88
+ if (response.status !== 202 || body !== "")
89
+ throw new Error(
90
+ `FavStash MCP protocol error: ${method} requires HTTP 202 with an empty body. Sign-in may have succeeded, but server initialization is not compatible; report this error instead of repeating OAuth.`,
91
+ );
92
+ },
93
+ };
94
+ }
package/bin/setup.js ADDED
@@ -0,0 +1,145 @@
1
+ import spawn from "cross-spawn";
2
+ import { fileURLToPath } from "node:url";
3
+ import { endpoint, configDirectory } from "./config.js";
4
+
5
+ function execute(command, args, { timeout }) {
6
+ return new Promise((resolve, reject) => {
7
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
8
+ let stdout = "",
9
+ stderr = "";
10
+ child.stdout.on("data", (chunk) => {
11
+ stdout += chunk;
12
+ });
13
+ child.stderr.on("data", (chunk) => {
14
+ stderr += chunk;
15
+ });
16
+ const timer = setTimeout(() => child.kill(), timeout);
17
+ child.once("error", (error) => {
18
+ clearTimeout(timer);
19
+ reject(error);
20
+ });
21
+ child.once("close", (code) => {
22
+ clearTimeout(timer);
23
+ if (code === 0) resolve({ stdout, stderr });
24
+ else
25
+ reject(
26
+ Object.assign(new Error("Host command failed"), {
27
+ code,
28
+ stdout,
29
+ stderr,
30
+ }),
31
+ );
32
+ });
33
+ });
34
+ }
35
+
36
+ export async function setupAgent(
37
+ agent,
38
+ { dryRun = false, run = execute } = {},
39
+ ) {
40
+ if (!["codex", "claude-code"].includes(agent))
41
+ throw new Error(
42
+ "Choose --agent codex or --agent claude-code. Other hosts: https://www.favstash.app/mcp",
43
+ );
44
+ const host = agent === "codex" ? "codex" : "claude";
45
+ const bridge = fileURLToPath(new URL("./favstash-mcp.js", import.meta.url));
46
+ const env = {
47
+ FAVSTASH_CONFIG_DIR: configDirectory(),
48
+ FAVSTASH_MCP_URL: endpoint(),
49
+ };
50
+ const environment = Object.entries(env).flatMap(([key, value]) => [
51
+ "--env",
52
+ `${key}=${value}`,
53
+ ]);
54
+ const add = [
55
+ "mcp",
56
+ "add",
57
+ ...(agent === "claude-code"
58
+ ? ["--scope", "user", "--transport", "stdio"]
59
+ : []),
60
+ "favstash",
61
+ ...environment,
62
+ "--",
63
+ process.execPath,
64
+ bridge,
65
+ ];
66
+ if (dryRun) return { agent, command: host, args: add, configured: false };
67
+ let existing;
68
+ try {
69
+ existing = await run(
70
+ host,
71
+ ["mcp", "get", "favstash", ...(agent === "codex" ? ["--json"] : [])],
72
+ { timeout: 15_000 },
73
+ );
74
+ } catch (error) {
75
+ if (error.code === "ENOENT")
76
+ throw new Error(
77
+ `${host} is not installed or is not on PATH. Install the host first.`,
78
+ );
79
+ const text = `${error.stdout || ""}\n${error.stderr || ""}`;
80
+ if (
81
+ !/not found|no .*server|does not exist|unknown server|no mcp server/i.test(
82
+ text,
83
+ )
84
+ )
85
+ throw new Error(
86
+ `Could not inspect ${host} MCP settings. Run ${host} mcp get favstash to diagnose before changing them.`,
87
+ );
88
+ }
89
+ if (existing) {
90
+ const output = existing.stdout || "";
91
+ let matches = false;
92
+ if (agent === "codex") {
93
+ try {
94
+ const current = JSON.parse(output);
95
+ const transport = current.transport;
96
+ matches =
97
+ current.enabled !== false &&
98
+ transport?.command === process.execPath &&
99
+ JSON.stringify(transport.args) === JSON.stringify([bridge]) &&
100
+ Object.keys(transport.env || {}).length === 2 &&
101
+ Object.entries(env).every(
102
+ ([key, value]) => transport.env?.[key] === value,
103
+ );
104
+ } catch {
105
+ /* Older host versions may not return a supported shape. */
106
+ }
107
+ } else {
108
+ // Claude exposes text here. Match complete fields, including our endpoint
109
+ // and credential directory, without reading or editing its settings file.
110
+ const lines = output.split(/\r?\n/).map((line) => line.trim());
111
+ matches =
112
+ lines.includes(`Command: ${process.execPath}`) &&
113
+ lines.includes(`Args: ${bridge}`) &&
114
+ Object.entries(env).every(
115
+ ([key, value]) =>
116
+ lines.includes(`${key}=${value}`) ||
117
+ lines.includes(`${key}: ${value}`),
118
+ ) &&
119
+ !output.includes("FAVSTASH_API_KEY");
120
+ }
121
+ if (matches)
122
+ return {
123
+ agent,
124
+ configured: true,
125
+ changed: false,
126
+ next: "Restart or reload your host, then verify FavStash tools.",
127
+ };
128
+ throw new Error(
129
+ `A favstash connection already exists. Inspect it with ${host} mcp get favstash. To migrate, save its configuration and remove only that entry with ${host} mcp remove ${agent === "claude-code" ? "--scope user " : ""}favstash, then rerun setup. No settings were changed.`,
130
+ );
131
+ }
132
+ try {
133
+ await run(host, add, { timeout: 15_000 });
134
+ } catch {
135
+ throw new Error(
136
+ `Could not add FavStash to ${host}. Run favstash setup --agent ${agent} --dry-run for the exact command. Other server entries were not changed.`,
137
+ );
138
+ }
139
+ return {
140
+ agent,
141
+ configured: true,
142
+ changed: true,
143
+ next: "Restart or reload the host, then verify FavStash tools. Configuration alone does not confirm authorization.",
144
+ };
145
+ }