@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.
- package/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +85 -91
- package/bin/auth.js +322 -0
- package/bin/bridge.js +118 -0
- package/bin/config.js +39 -0
- package/bin/contracts.js +142 -0
- package/bin/contracts.json +10249 -0
- package/bin/credential-store.js +198 -0
- package/bin/favstash-mcp.js +3 -562
- package/bin/favstash.js +175 -0
- package/bin/local-media-upload.js +19 -11
- package/bin/remote.js +94 -0
- package/bin/setup.js +145 -0
- package/bin/social-post-schema.js +33 -308
- package/package.json +25 -4
- package/skills/favstash/SKILL.md +17 -0
- package/bin/schema-registration.js +0 -28
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# @sketric/favstash-mcp
|
|
2
|
+
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Add the FavStash CLI with browser OAuth, OS-backed credential storage, automatic token refresh, Codex and Claude Code setup, and compatibility diagnostics. Generate bridge schemas from the hosted contracts, including X and current analytics inputs, while retaining API-key authentication and the favstash-mcp executable. Include public agent guides and an optional workflow skill.
|
|
8
|
+
- Verify the complete HTTP initialization lifecycle, including the empty notification acknowledgment required by strict clients, before discovery and one count-only `get_stash_summary` read. Reject mismatched JSON-RPC IDs, protocol errors, schema drift, and tool errors instead of reporting a false connection success.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sketric Solutions
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,102 +1,96 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Generated by scripts/generate-agent-docs.mjs. Edit the generator or agentConnectionData.ts. -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# FavStash CLI
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
filesystem-capable agent needs to publish a local image, video, or LinkedIn PDF
|
|
7
|
-
document**. Remote
|
|
8
|
-
Streamable HTTP clients that use only existing HTTPS media should connect
|
|
9
|
-
directly to `https://mcp.favstash.app/mcp` and use OAuth.
|
|
5
|
+
The npm package **@sketric/favstash-mcp** installs two commands: **favstash** for authentication, setup, and diagnostics; **favstash-mcp** for the local stdio MCP bridge. These are different parts of the same installation.
|
|
10
6
|
|
|
11
|
-
|
|
7
|
+
The bridge gives a local agent access to the hosted FavStash tools and can upload local files before forwarding a tool call. It is not a separate FavStash backend.
|
|
12
8
|
|
|
13
|
-
|
|
14
|
-
The bridge uses a locally stored FavStash API key; it does not reuse a host's
|
|
15
|
-
remote OAuth connection.
|
|
9
|
+
## Install and sign in
|
|
16
10
|
|
|
17
|
-
|
|
11
|
+
Recommended for Codex and Claude Code on a local computer with Node.js 20+. Check the registry before using the new commands:
|
|
18
12
|
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
FAVSTASH_MCP_URL=https://mcp.favstash.app/mcp \
|
|
22
|
-
npx -y @sketric/favstash-mcp
|
|
13
|
+
```sh
|
|
14
|
+
npm view @sketric/favstash-mcp version
|
|
23
15
|
```
|
|
24
16
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
17
|
+
Browser OAuth and the `favstash` command require **0.4.0+**. If npm reports an older version or cannot be reached, use the [remote OAuth alternative](https://www.favstash.app/mcp.md) and describe CLI setup as pending. Do not run commands that an older package does not provide.
|
|
18
|
+
|
|
19
|
+
For Codex:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install -g @sketric/favstash-mcp@latest
|
|
23
|
+
favstash auth login
|
|
24
|
+
favstash setup --agent codex
|
|
25
|
+
favstash doctor
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
For Claude Code, the commands are the same except:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
favstash setup --agent claude-code
|
|
40
32
|
```
|
|
41
33
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
The bridge registers the same 19 FavStash MCP v2 tool names as the hosted
|
|
48
|
-
endpoint, with local-file input added to the publishing tools.
|
|
49
|
-
Use `list_connected_social_accounts` before account-dependent work,
|
|
50
|
-
`get_social_account_analytics` for aggregate trends, and
|
|
51
|
-
`analyze_social_content_performance` for individual posts or rankings.
|
|
52
|
-
Agents can create a date-only calendar plan by calling `create_social_post`
|
|
53
|
-
with `draft=true` and `plannedDate="YYYY-MM-DD"`. A planned draft never
|
|
54
|
-
publishes automatically; scheduling it later still requires `publishAt`.
|
|
55
|
-
Instagram, YouTube, TikTok, and LinkedIn personal accounts are publishing
|
|
56
|
-
destinations. LinkedIn personal accounts are publishing-only: the self-serve
|
|
57
|
-
API does not expose their analytics or owned-post history.
|
|
58
|
-
|
|
59
|
-
For ordinary publishing, pass an absolute `media[].localPath` and optional
|
|
60
|
-
`media[].thumbnailPath` directly to `create_social_post` or
|
|
61
|
-
`update_social_post`. Root content/media are shared defaults; a target may carry
|
|
62
|
-
its own `content` and `media` when a channel needs a different caption or asset.
|
|
63
|
-
The bridge resolves local paths in both locations, validates regular-file
|
|
64
|
-
status, extension, magic bytes, and size, and validates the complete typed
|
|
65
|
-
platform, publishing-mode, and statically known media-compatibility contract
|
|
66
|
-
before reading or uploading a file. This includes each destination's effective
|
|
67
|
-
caption limit and rejects LinkedIn MOV video before transfer. It then hides presign, streaming PUT,
|
|
68
|
-
multipart retries, ETags, completion, and CDN substitution inside the same tool
|
|
69
|
-
call. It hashes files while preparing them so
|
|
70
|
-
an exact retry resolves to the same content-addressed CDN URL; conditional
|
|
71
|
-
storage writes make that object immutable, and backend completion streams and
|
|
72
|
-
verifies every uploaded byte against the digest in the key. A conflicting or
|
|
73
|
-
truncated first write is deleted instead of being accepted, so a retry cannot
|
|
74
|
-
silently reference different media. This remains compatible with
|
|
75
|
-
`clientRequestId`-based post idempotency. Images may be up to 8 MB, PDF
|
|
76
|
-
documents up to 100 MB, video up to 200 MB, and JPEG/PNG thumbnails up to 2 MB.
|
|
77
|
-
A PDF is valid only as the sole media item on a LinkedIn target; its filename
|
|
78
|
-
becomes the document title unless `title` is provided.
|
|
79
|
-
For a planned YouTube or TikTok draft, a non-empty provider
|
|
80
|
-
`target.settings.title` also counts as meaningful draft content, matching the
|
|
81
|
-
hosted contract.
|
|
82
|
-
|
|
83
|
-
`create_social_post` requires a 16–128 character `clientRequestId` beginning
|
|
84
|
-
with a letter or number; reuse it only for an exact retry of the same request.
|
|
85
|
-
The hosted backend uses that key to prevent a lost response from creating
|
|
86
|
-
another post.
|
|
87
|
-
|
|
88
|
-
`update_social_post` requires `expectedUpdatedAt` from `get_social_post` or
|
|
89
|
-
`list_social_posts`. FavStash rejects the update if a newer web, mobile, or
|
|
90
|
-
agent edit has already changed that version.
|
|
91
|
-
|
|
92
|
-
Use `import_post_media` only for explicit staging or reuse. It accepts one HTTPS
|
|
93
|
-
`url`, one local `path`, or up to ten ordered local `files[]` entries. A
|
|
94
|
-
singular URL or path also accepts a 1–200 character PDF `title`. Agents
|
|
95
|
-
must not reuse the configured bearer credential outside the bridge, call the
|
|
96
|
-
FavStash upload routes themselves, or expose signed upload details.
|
|
97
|
-
|
|
98
|
-
For local development from the repository root:
|
|
99
|
-
|
|
100
|
-
```bash
|
|
101
|
-
FAVSTASH_API_KEY=favstash_pk_... node packages/favstash-mcp/bin/favstash-mcp.js
|
|
34
|
+
Complete sign-in and consent in the browser. Reload the owning agent after adding the bridge. Then ask:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
Use FavStash's get_stash_summary tool once with no filters. Report whether it succeeded and the returned counts. Zero counts are valid. Do not modify any data.
|
|
102
38
|
```
|
|
39
|
+
|
|
40
|
+
Zero counts are valid. `doctor` verifies the full authenticated handshake, tool schemas, and one count-only read. The host still needs its own read-only verification after reload. Do not publish a post as a connection test.
|
|
41
|
+
|
|
42
|
+
## One prompt
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
Install FavStash in this agent by following https://www.favstash.app/INSTALL_FOR_AGENTS.md; you may configure only the FavStash MCP connection, request permission if required, complete browser sign-in with me, and verify a read-only tool call before reporting success.
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The setup helper uses the installed host CLI and adds only the `favstash` entry. It pins the bridge to this installation’s absolute Node and script paths, so use a stable global installation, not a temporary npx cache. Existing entries are preserved; inspect and save an older entry before manually migrating it. Do not replace an entire host config file. If Node is moved or upgraded to another installation path, rerun setup and review the migration instructions.
|
|
49
|
+
|
|
50
|
+
## Commands
|
|
51
|
+
|
|
52
|
+
| Command | Purpose |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `favstash auth login` | Browser OAuth with PKCE; approve access yourself |
|
|
55
|
+
| `favstash auth login --no-browser` | Print the sign-in URL instead of opening it |
|
|
56
|
+
| `favstash auth status` | Redacted local session state; not a live authorization check |
|
|
57
|
+
| `favstash auth logout` | Revoke the session and remove local credentials |
|
|
58
|
+
| `favstash setup --agent codex` | Configure Codex with the local bridge |
|
|
59
|
+
| `favstash setup --agent claude-code` | Configure Claude Code at user scope |
|
|
60
|
+
| `favstash setup --agent codex --dry-run` | Preview configuration without changing it |
|
|
61
|
+
| `favstash doctor` | Check the full handshake, hosted schemas, and a count-only read |
|
|
62
|
+
| `favstash tools` | Print the local tool catalogue as JSON, without credentials |
|
|
63
|
+
| `favstash mcp` / `favstash-mcp` | Start the bridge over stdin/stdout |
|
|
64
|
+
|
|
65
|
+
Results are JSON on stdout. Instructions and errors use stderr. Exit 0 is success, 1 is a command/authentication failure, and doctor exits 2 on a schema mismatch. Check `--help` for the installed version’s options.
|
|
66
|
+
|
|
67
|
+
## Credentials and headless environments
|
|
68
|
+
|
|
69
|
+
The default uses the OS credential store for an encryption key and an encrypted session file under `~/.config/favstash` (or `XDG_CONFIG_HOME/favstash`). Tokens refresh automatically. Multiple agent processes share a lock so refresh-token rotation is serialized.
|
|
70
|
+
|
|
71
|
+
If the OS store is unavailable, unlock or configure it. Only on a private machine, explicitly choose `favstash auth login --credential-store file`; this uses a private local file rather than OS-backed encryption. POSIX directory/file modes are 700/600; on Windows, use a private user profile and appropriate filesystem ACLs. There is no silent fallback.
|
|
72
|
+
|
|
73
|
+
The browser must reach the CLI’s `127.0.0.1` callback. `--no-browser` does not turn this into a device-code flow. SSH, containers, and cloud agents need a reachable callback, a host-managed OAuth connection, or a securely supplied API key. They cannot silently configure a separate computer.
|
|
74
|
+
|
|
75
|
+
`FAVSTASH_API_KEY` takes precedence over OAuth for unattended jobs. Set it through local secret storage, never in a chat, committed config, or command history. `FAVSTASH_MCP_URL` selects another trusted endpoint; `FAVSTASH_CONFIG_DIR` selects an isolated credential directory. The setup helper passes the selected endpoint and directory to the bridge.
|
|
76
|
+
|
|
77
|
+
Logout retains local credentials if server revocation fails, so it can be retried. `--local-only` explicitly forgets local credentials without revoking remote access. It does not unset an API key supplied by the environment.
|
|
78
|
+
|
|
79
|
+
## Local media and discovery
|
|
80
|
+
|
|
81
|
+
The bridge advertises the hosted tools with local-media extensions. For `create_social_post` / `update_social_post`, use `media: [{ localPath: "/absolute/path/file.mp4" }]` or the same shape on a target. For `import_post_media`, use `path` or `files`. Inspect `favstash tools` for the exact schema before calling. Use an explicit media kind where required by the current schema. Remote MCP clients use server-fetchable HTTPS URLs instead.
|
|
82
|
+
|
|
83
|
+
Local validation runs before upload. The bridge imports the file into FavStash media storage, substitutes the resulting HTTPS reference, and forwards the original operation. Publishing still needs the user’s explicit instruction. Provider credentials stay on FavStash’s backend.
|
|
84
|
+
|
|
85
|
+
## Updates and optional skills
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
npm install -g @sketric/favstash-mcp@latest
|
|
89
|
+
favstash doctor
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Restart the agent after updating. Package versions use SemVer independently from web/mobile releases; generated contracts and release checks prevent silent schema drift. API keys and the `favstash-mcp` executable remain supported.
|
|
93
|
+
|
|
94
|
+
An optional [FavStash workflow skill](https://www.favstash.app/skills/favstash/SKILL.md) teaches discovery, read-before-write, and media handling. Ask your agent to install it with its usual skill installer. It is also included in the npm package. The skill does not connect or authenticate an account.
|
|
95
|
+
|
|
96
|
+
[Remote MCP](https://www.favstash.app/mcp) · [API](https://www.favstash.app/api) · [Tool reference](https://www.favstash.app/docs/tools-reference) · [npm](https://www.npmjs.com/package/@sketric/favstash-mcp)
|
package/bin/auth.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import {
|
|
5
|
+
auth,
|
|
6
|
+
discoverOAuthServerInfo,
|
|
7
|
+
} from "@modelcontextprotocol/sdk/client/auth.js";
|
|
8
|
+
import { credentialStore } from "./credential-store.js";
|
|
9
|
+
import { endpoint } from "./config.js";
|
|
10
|
+
|
|
11
|
+
export function openBrowser(url) {
|
|
12
|
+
const [command, args] =
|
|
13
|
+
process.platform === "darwin"
|
|
14
|
+
? ["open", [url]]
|
|
15
|
+
: process.platform === "win32"
|
|
16
|
+
? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
17
|
+
: ["xdg-open", [url]];
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
const child = spawn(command, args, { stdio: "ignore", shell: false });
|
|
20
|
+
child.once("error", reject);
|
|
21
|
+
child.once("exit", (code) =>
|
|
22
|
+
code === 0
|
|
23
|
+
? resolve()
|
|
24
|
+
: reject(new Error("Browser could not be opened.")),
|
|
25
|
+
);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// FavStash's OAuth facade is same-origin. Discovery must never send an existing
|
|
30
|
+
// credential, verifier, or refresh token to a different authority or redirect.
|
|
31
|
+
export function oauthFetch(url, fetchImpl = fetch) {
|
|
32
|
+
const origin = new URL(url).origin;
|
|
33
|
+
return async (input, init) => {
|
|
34
|
+
const target = new URL(input instanceof Request ? input.url : input);
|
|
35
|
+
if (target.origin !== origin)
|
|
36
|
+
throw new Error(
|
|
37
|
+
"OAuth endpoint changed origin. Reconnect using a trusted FavStash endpoint.",
|
|
38
|
+
);
|
|
39
|
+
return fetchImpl(input, {
|
|
40
|
+
...init,
|
|
41
|
+
redirect: "error",
|
|
42
|
+
signal: init?.signal || AbortSignal.timeout(30_000),
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function providerFor(state, onRedirect, stateValue) {
|
|
48
|
+
let verifier;
|
|
49
|
+
return {
|
|
50
|
+
get redirectUrl() {
|
|
51
|
+
return state.redirectUri;
|
|
52
|
+
},
|
|
53
|
+
get clientMetadata() {
|
|
54
|
+
return {
|
|
55
|
+
client_name: "FavStash CLI",
|
|
56
|
+
redirect_uris: [state.redirectUri],
|
|
57
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
58
|
+
response_types: ["code"],
|
|
59
|
+
token_endpoint_auth_method: "none",
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
state: () => stateValue,
|
|
63
|
+
clientInformation: () => state.clientInformation,
|
|
64
|
+
saveClientInformation: (value) => {
|
|
65
|
+
state.clientInformation = value;
|
|
66
|
+
},
|
|
67
|
+
tokens: () => state.tokens,
|
|
68
|
+
saveTokens: (tokens) => {
|
|
69
|
+
state.tokens = tokens;
|
|
70
|
+
state.expiresAt = Date.now() + (tokens.expires_in ?? 0) * 1000;
|
|
71
|
+
},
|
|
72
|
+
saveCodeVerifier: (value) => {
|
|
73
|
+
verifier = value;
|
|
74
|
+
},
|
|
75
|
+
codeVerifier: () => {
|
|
76
|
+
if (!verifier)
|
|
77
|
+
throw new Error("Missing PKCE verifier. Start login again.");
|
|
78
|
+
return verifier;
|
|
79
|
+
},
|
|
80
|
+
redirectToAuthorization: onRedirect,
|
|
81
|
+
invalidateCredentials: (scope) => {
|
|
82
|
+
if (scope === "all" || scope === "tokens") delete state.tokens;
|
|
83
|
+
if (scope === "all" || scope === "client") delete state.clientInformation;
|
|
84
|
+
if (scope === "all" || scope === "verifier") verifier = undefined;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function callbackListener(
|
|
90
|
+
expectedState,
|
|
91
|
+
{ timeoutMs = 5 * 60_000 } = {},
|
|
92
|
+
) {
|
|
93
|
+
let finish, fail, timer;
|
|
94
|
+
const code = new Promise((resolve, reject) => {
|
|
95
|
+
finish = resolve;
|
|
96
|
+
fail = reject;
|
|
97
|
+
});
|
|
98
|
+
// A failed discovery can finish before anyone awaits the callback.
|
|
99
|
+
code.catch(() => {});
|
|
100
|
+
const server = createServer((request, response) => {
|
|
101
|
+
const received = new URL(request.url || "/", "http://127.0.0.1");
|
|
102
|
+
const address = server.address();
|
|
103
|
+
if (
|
|
104
|
+
request.method !== "GET" ||
|
|
105
|
+
received.pathname !== "/oauth/callback" ||
|
|
106
|
+
request.headers.host !== `127.0.0.1:${address.port}`
|
|
107
|
+
) {
|
|
108
|
+
response.writeHead(404).end();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const incoming = Buffer.from(received.searchParams.get("state") || "");
|
|
112
|
+
const wanted = Buffer.from(expectedState);
|
|
113
|
+
if (
|
|
114
|
+
incoming.length !== wanted.length ||
|
|
115
|
+
!timingSafeEqual(incoming, wanted)
|
|
116
|
+
) {
|
|
117
|
+
response.writeHead(400).end("Invalid OAuth state.");
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
response.setHeader("Cache-Control", "no-store");
|
|
121
|
+
response.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
122
|
+
response.setHeader(
|
|
123
|
+
"Content-Security-Policy",
|
|
124
|
+
"default-src 'none'; frame-ancestors 'none'",
|
|
125
|
+
);
|
|
126
|
+
const authorizationCode = received.searchParams.get("code");
|
|
127
|
+
if (received.searchParams.has("error") || !authorizationCode) {
|
|
128
|
+
response
|
|
129
|
+
.writeHead(400)
|
|
130
|
+
.end("FavStash access was not approved. Return to your terminal.");
|
|
131
|
+
fail(
|
|
132
|
+
new Error(
|
|
133
|
+
"Sign-in was cancelled or denied. Run favstash auth login to try again.",
|
|
134
|
+
),
|
|
135
|
+
);
|
|
136
|
+
} else {
|
|
137
|
+
response.end(
|
|
138
|
+
"Authorization received. Return to your terminal to finish connecting FavStash.",
|
|
139
|
+
);
|
|
140
|
+
finish(authorizationCode);
|
|
141
|
+
}
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
});
|
|
144
|
+
await new Promise((resolve, reject) => {
|
|
145
|
+
server.once("error", reject);
|
|
146
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
147
|
+
});
|
|
148
|
+
timer = setTimeout(
|
|
149
|
+
() => fail(new Error("Sign-in timed out. Run favstash auth login again.")),
|
|
150
|
+
timeoutMs,
|
|
151
|
+
);
|
|
152
|
+
return {
|
|
153
|
+
redirectUri: `http://127.0.0.1:${server.address().port}/oauth/callback`,
|
|
154
|
+
code,
|
|
155
|
+
async close() {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
server.closeAllConnections();
|
|
158
|
+
await new Promise((resolve) => server.close(resolve));
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export async function login({
|
|
164
|
+
url = endpoint(),
|
|
165
|
+
storage = "keychain",
|
|
166
|
+
noBrowser = false,
|
|
167
|
+
store = credentialStore(url),
|
|
168
|
+
fetchImpl = fetch,
|
|
169
|
+
browser = openBrowser,
|
|
170
|
+
log = console.error,
|
|
171
|
+
timeoutMs,
|
|
172
|
+
} = {}) {
|
|
173
|
+
return store.locked(async () => {
|
|
174
|
+
await store.prepare(storage);
|
|
175
|
+
const stateValue = randomBytes(32).toString("base64url");
|
|
176
|
+
const listener = await callbackListener(stateValue, { timeoutMs });
|
|
177
|
+
const state = { endpoint: url, storage, redirectUri: listener.redirectUri };
|
|
178
|
+
const provider = providerFor(
|
|
179
|
+
state,
|
|
180
|
+
async (authorizationUrl) => {
|
|
181
|
+
log(
|
|
182
|
+
`Complete FavStash sign-in and approve access in your browser:\n${authorizationUrl.href}`,
|
|
183
|
+
);
|
|
184
|
+
if (!noBrowser)
|
|
185
|
+
await browser(authorizationUrl.href).catch(() =>
|
|
186
|
+
log("Open the sign-in link above on this computer."),
|
|
187
|
+
);
|
|
188
|
+
},
|
|
189
|
+
stateValue,
|
|
190
|
+
);
|
|
191
|
+
try {
|
|
192
|
+
// Let the SDK use protected-resource discovery. Scope identifiers need
|
|
193
|
+
// not share the endpoint hostname (for example on the shared sandbox).
|
|
194
|
+
const result = await auth(provider, {
|
|
195
|
+
serverUrl: url,
|
|
196
|
+
fetchFn: oauthFetch(url, fetchImpl),
|
|
197
|
+
});
|
|
198
|
+
if (result === "REDIRECT") {
|
|
199
|
+
await auth(provider, {
|
|
200
|
+
serverUrl: url,
|
|
201
|
+
authorizationCode: await listener.code,
|
|
202
|
+
fetchFn: oauthFetch(url, fetchImpl),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
if (!state.tokens?.access_token || !state.tokens?.refresh_token)
|
|
206
|
+
throw new Error(
|
|
207
|
+
"FavStash did not issue a complete session. Start login again.",
|
|
208
|
+
);
|
|
209
|
+
await store.write(state);
|
|
210
|
+
return {
|
|
211
|
+
authenticated: true,
|
|
212
|
+
storage,
|
|
213
|
+
endpoint: url,
|
|
214
|
+
scopes: state.tokens.scope?.split(" ") || [],
|
|
215
|
+
};
|
|
216
|
+
} finally {
|
|
217
|
+
await listener.close();
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export async function accessToken({
|
|
223
|
+
url = endpoint(),
|
|
224
|
+
store = credentialStore(url),
|
|
225
|
+
fetchImpl = fetch,
|
|
226
|
+
apiKey = process.env.FAVSTASH_API_KEY,
|
|
227
|
+
rejectedToken,
|
|
228
|
+
} = {}) {
|
|
229
|
+
if (apiKey) return apiKey;
|
|
230
|
+
return store.locked(async () => {
|
|
231
|
+
const state = await store.read();
|
|
232
|
+
if (!state?.tokens?.access_token)
|
|
233
|
+
throw new Error(
|
|
234
|
+
"Not signed in. Run favstash auth login, then retry. FAVSTASH_API_KEY remains available for automation.",
|
|
235
|
+
);
|
|
236
|
+
if (
|
|
237
|
+
state.expiresAt > Date.now() + 60_000 &&
|
|
238
|
+
state.tokens.access_token !== rejectedToken
|
|
239
|
+
)
|
|
240
|
+
return state.tokens.access_token;
|
|
241
|
+
const provider = providerFor(state, () => {
|
|
242
|
+
throw new Error(
|
|
243
|
+
"Session expired or revoked. Run favstash auth login again.",
|
|
244
|
+
);
|
|
245
|
+
});
|
|
246
|
+
const result = await auth(provider, {
|
|
247
|
+
serverUrl: url,
|
|
248
|
+
fetchFn: oauthFetch(url, fetchImpl),
|
|
249
|
+
});
|
|
250
|
+
if (result !== "AUTHORIZED" || !state.tokens?.access_token)
|
|
251
|
+
throw new Error("Session expired. Run favstash auth login again.");
|
|
252
|
+
await store.write(state);
|
|
253
|
+
return state.tokens.access_token;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export async function authStatus({
|
|
258
|
+
url = endpoint(),
|
|
259
|
+
store = credentialStore(url),
|
|
260
|
+
apiKey = process.env.FAVSTASH_API_KEY,
|
|
261
|
+
} = {}) {
|
|
262
|
+
if (apiKey)
|
|
263
|
+
return {
|
|
264
|
+
authenticated: true,
|
|
265
|
+
method: "api-key",
|
|
266
|
+
endpoint: url,
|
|
267
|
+
verified: false,
|
|
268
|
+
};
|
|
269
|
+
const state = await store.read();
|
|
270
|
+
return {
|
|
271
|
+
authenticated: Boolean(state?.tokens),
|
|
272
|
+
method: "oauth",
|
|
273
|
+
endpoint: url,
|
|
274
|
+
storage: state?.storage,
|
|
275
|
+
expired: state?.expiresAt ? state.expiresAt <= Date.now() : undefined,
|
|
276
|
+
scopes: state?.tokens?.scope?.split(" ") || [],
|
|
277
|
+
verified: false,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export async function logout({
|
|
282
|
+
url = endpoint(),
|
|
283
|
+
store = credentialStore(url),
|
|
284
|
+
fetchImpl = fetch,
|
|
285
|
+
localOnly = false,
|
|
286
|
+
} = {}) {
|
|
287
|
+
return store.locked(async () => {
|
|
288
|
+
const state = localOnly ? undefined : await store.read();
|
|
289
|
+
if (state?.tokens?.refresh_token && !localOnly) {
|
|
290
|
+
const request = oauthFetch(url, fetchImpl);
|
|
291
|
+
const { authorizationServerMetadata: metadata } =
|
|
292
|
+
await discoverOAuthServerInfo(url, { fetchFn: request });
|
|
293
|
+
if (!metadata)
|
|
294
|
+
throw new Error(
|
|
295
|
+
"Could not discover revocation. Retry logout, or use --local-only to remove local credentials without server revocation.",
|
|
296
|
+
);
|
|
297
|
+
if (!metadata.revocation_endpoint)
|
|
298
|
+
throw new Error(
|
|
299
|
+
"Server does not advertise revocation. Use --local-only only to forget local credentials.",
|
|
300
|
+
);
|
|
301
|
+
const response = await request(metadata.revocation_endpoint, {
|
|
302
|
+
method: "POST",
|
|
303
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
304
|
+
body: new URLSearchParams({
|
|
305
|
+
token: state.tokens.refresh_token,
|
|
306
|
+
token_type_hint: "refresh_token",
|
|
307
|
+
client_id: state.clientInformation.client_id,
|
|
308
|
+
}),
|
|
309
|
+
});
|
|
310
|
+
if (!response.ok)
|
|
311
|
+
throw new Error(
|
|
312
|
+
"Revocation failed. Credentials were retained so logout can be retried.",
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
await store.clear({ bestEffortKeychain: localOnly });
|
|
316
|
+
return {
|
|
317
|
+
signedOut: true,
|
|
318
|
+
revoked: Boolean(state?.tokens?.refresh_token && !localOnly),
|
|
319
|
+
apiKeyEnvironmentUnchanged: Boolean(process.env.FAVSTASH_API_KEY),
|
|
320
|
+
};
|
|
321
|
+
});
|
|
322
|
+
}
|
package/bin/bridge.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
|
+
import {
|
|
4
|
+
CallToolRequestSchema,
|
|
5
|
+
ListToolsRequestSchema,
|
|
6
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { localTools, localValidation, validate } from "./contracts.js";
|
|
8
|
+
import { PACKAGE, endpoint } from "./config.js";
|
|
9
|
+
import { remoteClient } from "./remote.js";
|
|
10
|
+
import {
|
|
11
|
+
createLocalMediaUploadClient,
|
|
12
|
+
deriveApiBaseUrl,
|
|
13
|
+
normalizeLocalPostArguments,
|
|
14
|
+
} from "./local-media-upload.js";
|
|
15
|
+
import {
|
|
16
|
+
hasMeaningfulPostContent,
|
|
17
|
+
validatePublishTargetsBeforeUpload,
|
|
18
|
+
} from "./social-post-schema.js";
|
|
19
|
+
|
|
20
|
+
function toolResult(value) {
|
|
21
|
+
return {
|
|
22
|
+
content: [{ type: "text", text: JSON.stringify(value) }],
|
|
23
|
+
structuredContent: value,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createBridge({
|
|
28
|
+
url = endpoint(),
|
|
29
|
+
remote = remoteClient({ url }),
|
|
30
|
+
uploadClient,
|
|
31
|
+
} = {}) {
|
|
32
|
+
const uploads =
|
|
33
|
+
uploadClient ||
|
|
34
|
+
createLocalMediaUploadClient({
|
|
35
|
+
apiBaseUrl: deriveApiBaseUrl(url, process.env.FAVSTASH_API_URL),
|
|
36
|
+
authorizedFetch: remote.authorizedFetch,
|
|
37
|
+
});
|
|
38
|
+
const server = new Server(
|
|
39
|
+
{ name: "favstash", version: PACKAGE.version },
|
|
40
|
+
{
|
|
41
|
+
capabilities: { tools: {} },
|
|
42
|
+
instructions:
|
|
43
|
+
"FavStash local bridge. Search saved inspiration, discover connected social accounts before analytics or publishing, and follow returned nextActions. Local files are uploaded inside post tools. Obtain user authorization for publishing and destructive changes. If authentication is missing, run favstash auth login in the terminal; never request credentials in chat.",
|
|
44
|
+
},
|
|
45
|
+
);
|
|
46
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
47
|
+
tools: localTools,
|
|
48
|
+
}));
|
|
49
|
+
server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
|
|
50
|
+
try {
|
|
51
|
+
const schema = localValidation.get(params.name);
|
|
52
|
+
if (!schema) throw new Error(`Unknown FavStash tool: ${params.name}`);
|
|
53
|
+
const args = validate(schema, params.arguments || {});
|
|
54
|
+
if (params.name === "create_social_post") {
|
|
55
|
+
if (!hasMeaningfulPostContent(args))
|
|
56
|
+
throw new Error("Provide a caption, title, or media.");
|
|
57
|
+
const issues = [];
|
|
58
|
+
validatePublishTargetsBeforeUpload(args, {
|
|
59
|
+
addIssue: (issue) => issues.push(issue),
|
|
60
|
+
});
|
|
61
|
+
if (issues.length)
|
|
62
|
+
throw new Error(issues.map((issue) => issue.message).join("; "));
|
|
63
|
+
}
|
|
64
|
+
if (
|
|
65
|
+
params.name === "update_social_post" &&
|
|
66
|
+
args.publishAt &&
|
|
67
|
+
args.plannedDate
|
|
68
|
+
)
|
|
69
|
+
throw new Error("Provide plannedDate or publishAt, not both.");
|
|
70
|
+
if (["create_social_post", "update_social_post"].includes(params.name)) {
|
|
71
|
+
return remote.rpc("tools/call", {
|
|
72
|
+
name: params.name,
|
|
73
|
+
arguments: await normalizeLocalPostArguments(args, uploads),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
if (params.name === "import_post_media" && !args.url) {
|
|
77
|
+
const files = args.path
|
|
78
|
+
? [{ path: args.path, role: args.role || "media" }]
|
|
79
|
+
: args.files;
|
|
80
|
+
const prepared = [];
|
|
81
|
+
for (const file of files)
|
|
82
|
+
prepared.push({
|
|
83
|
+
...(await uploads.prepareFile(file.path, file.role || "media")),
|
|
84
|
+
role: file.role || "media",
|
|
85
|
+
});
|
|
86
|
+
const imports = [];
|
|
87
|
+
for (const file of prepared)
|
|
88
|
+
imports.push({
|
|
89
|
+
...(await uploads.uploadPreparedFile(file)),
|
|
90
|
+
role: file.role,
|
|
91
|
+
});
|
|
92
|
+
if (!args.path) return toolResult({ imports, count: imports.length });
|
|
93
|
+
return toolResult({
|
|
94
|
+
...imports[0],
|
|
95
|
+
...(args.title && imports[0].type === "document"
|
|
96
|
+
? { title: args.title }
|
|
97
|
+
: {}),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return remote.rpc("tools/call", { name: params.name, arguments: args });
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return {
|
|
103
|
+
isError: true,
|
|
104
|
+
content: [{ type: "text", text: error.message }],
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
return server;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function startBridge() {
|
|
112
|
+
const server = createBridge();
|
|
113
|
+
await server.connect(new StdioServerTransport());
|
|
114
|
+
console.error(
|
|
115
|
+
`FavStash ${PACKAGE.version} local bridge ready. Run favstash doctor to verify account access.`,
|
|
116
|
+
);
|
|
117
|
+
return server;
|
|
118
|
+
}
|