@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/LICENSE +21 -0
- package/README.md +130 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +87 -0
- package/dist/client.d.ts +52 -0
- package/dist/client.js +221 -0
- package/dist/config.d.ts +24 -0
- package/dist/config.js +61 -0
- package/dist/http.d.ts +10 -0
- package/dist/http.js +138 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/login.d.ts +32 -0
- package/dist/login.js +140 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +59 -0
- package/dist/token-store.d.ts +20 -0
- package/dist/token-store.js +49 -0
- package/dist/tools.d.ts +5 -0
- package/dist/tools.js +183 -0
- package/dist/uploads.d.ts +36 -0
- package/dist/uploads.js +57 -0
- package/package.json +47 -4
- package/skill/SKILL.md +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mjrealm
|
|
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,3 +1,131 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wardrowbe-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) server for [Wardrowbe](https://github.com/Anyesh/wardrowbe), the self-hosted wardrobe app. It lets any MCP client list and inspect items, log wear and washes, suggest outfits, and check analytics.
|
|
4
|
+
|
|
5
|
+
Requires Node.js 20 or newer.
|
|
6
|
+
|
|
7
|
+
## Quick start
|
|
8
|
+
|
|
9
|
+
You need your Wardrowbe URL and an OIDC client for Wardrowbe. Pocket ID works.
|
|
10
|
+
|
|
11
|
+
1. In your IdP, create a public client with PKCE. Allow the scopes `openid profile email offline_access`, and add the redirect URI `http://localhost:8765/callback`.
|
|
12
|
+
2. Add the server to your MCP client. For Claude Desktop or Claude Code:
|
|
13
|
+
|
|
14
|
+
```json
|
|
15
|
+
{
|
|
16
|
+
"mcpServers": {
|
|
17
|
+
"wardrowbe": {
|
|
18
|
+
"command": "npx",
|
|
19
|
+
"args": ["-y", "@mdeleon23/wardrowbe-mcp"],
|
|
20
|
+
"env": {
|
|
21
|
+
"WARDROWBE_URL": "https://wardrowbe.example.com",
|
|
22
|
+
"OIDC_ISSUER_URL": "https://pocket.example.com",
|
|
23
|
+
"OIDC_CLIENT_ID": "wardrowbe"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
3. Call `list_items` from your client. The first time, your browser opens for sign-in. After that, the refresh token is saved and you won't be asked again.
|
|
31
|
+
|
|
32
|
+
To use a plain access token instead, set `WARDROWBE_TOKEN` in place of the `OIDC_*` variables. It expires, so OIDC is better for regular use.
|
|
33
|
+
|
|
34
|
+
## Configuration
|
|
35
|
+
|
|
36
|
+
| Variable | Required | Default | Purpose |
|
|
37
|
+
| --- | --- | --- | --- |
|
|
38
|
+
| `WARDROWBE_URL` | yes | | Base URL of your Wardrowbe instance. |
|
|
39
|
+
| `WARDROWBE_TOKEN` | or OIDC | | A Wardrowbe access token (JWT). |
|
|
40
|
+
| `OIDC_ISSUER_URL` | or token | | OIDC issuer, e.g. `https://pocket.example.com`. |
|
|
41
|
+
| `OIDC_CLIENT_ID` | with OIDC | | OIDC client ID. |
|
|
42
|
+
| `OIDC_CLIENT_SECRET` | no | | Only for confidential clients. |
|
|
43
|
+
| `OIDC_REFRESH_TOKEN` | no | | Use this refresh token instead of the saved one. For headless hosts (see below). |
|
|
44
|
+
| `WARDROWBE_TOKEN_FILE` | no | `~/.config/wardrowbe-mcp/refresh-token.json` | Where the refresh token is saved. |
|
|
45
|
+
| `MCP_TRANSPORT` | no | `stdio` | `stdio` or `http`. |
|
|
46
|
+
| `MCP_BIND_HOST` | no | `127.0.0.1` | Address for HTTP. Use `0.0.0.0` in containers. |
|
|
47
|
+
| `MCP_PORT` | no | `8080` | Port for HTTP. |
|
|
48
|
+
| `MCP_API_KEY` | http only | | Bearer key that clients send to `/mcp`. |
|
|
49
|
+
|
|
50
|
+
## How sign-in works
|
|
51
|
+
|
|
52
|
+
With OIDC set, the server signs in through your browser the first time a tool needs a token. It catches the redirect on `localhost:8765`, then saves the refresh token to `WARDROWBE_TOKEN_FILE` with owner-only permissions. Later runs reuse it. If the token is revoked, the server signs in once more.
|
|
53
|
+
|
|
54
|
+
The browser sign-in needs a browser on the same machine as the server. On a headless host or in a container, sign in elsewhere and pass the token in:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npx -y @mdeleon23/wardrowbe-mcp login --issuer https://pocket.example.com --client-id wardrowbe > refresh-token.txt
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Then set `OIDC_REFRESH_TOKEN` to the contents of `refresh-token.txt`, and delete the file.
|
|
61
|
+
|
|
62
|
+
## HTTP transport
|
|
63
|
+
|
|
64
|
+
For MCPHub or any client that connects to a URL:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
MCP_TRANSPORT=http \
|
|
68
|
+
MCP_BIND_HOST=0.0.0.0 \
|
|
69
|
+
MCP_API_KEY="$(openssl rand -hex 32)" \
|
|
70
|
+
WARDROWBE_URL=https://wardrowbe.example.com \
|
|
71
|
+
OIDC_ISSUER_URL=https://pocket.example.com \
|
|
72
|
+
OIDC_CLIENT_ID=wardrowbe \
|
|
73
|
+
OIDC_REFRESH_TOKEN=<refresh-token> \
|
|
74
|
+
npx -y @mdeleon23/wardrowbe-mcp
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Register the server at `http://<host>:8080/mcp` with the header `Authorization: Bearer <MCP_API_KEY>`. `GET /` returns a small info response without auth.
|
|
78
|
+
|
|
79
|
+
### Adding items from photos
|
|
80
|
+
|
|
81
|
+
Photos go to the server directly, not through the AI, so the model never has to handle image bytes:
|
|
82
|
+
|
|
83
|
+
1. The app uploads the photo to `POST /uploads` with the same Bearer key. Send the raw image as the body, with `Content-Type` set to `image/jpeg`, `image/png`, `image/webp`, or `image/heic`. Optionally set `X-Filename` (URL-encoded).
|
|
84
|
+
2. The response is `{"upload_id": "...", "expires_in_seconds": 600}`.
|
|
85
|
+
3. The agent calls `add_item` with that `upload_id`. The upload is used once and then deleted. Uploads over 15 MB are refused, and uploads expire after 10 minutes.
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
curl -s -X POST https://<host>:8080/uploads \
|
|
89
|
+
-H "Authorization: Bearer <MCP_API_KEY>" \
|
|
90
|
+
-H "Content-Type: image/jpeg" \
|
|
91
|
+
-H "X-Filename: blue-shirt.jpg" \
|
|
92
|
+
--data-binary @blue-shirt.jpg
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
An agent can also do the whole thing through MCP with the `upload_photo` tool, which takes the photo as base64 (up to 300 KB) and returns an `upload_id` for `add_item`. The model has to write the image out in full, so keep photos small for this route. Full-size phone photos should go through `/uploads`.
|
|
96
|
+
|
|
97
|
+
`add_item` works over stdio too, as long as the `upload_id` came from `upload_photo` in the same server process. `/uploads` is HTTP only.
|
|
98
|
+
|
|
99
|
+
## Tools
|
|
100
|
+
|
|
101
|
+
| Tool | Wardrowbe endpoint | Notes |
|
|
102
|
+
| --- | --- | --- |
|
|
103
|
+
| `list_items` | `GET /items` | Filter by type, status, favorites, needs wash, search. Paginated. |
|
|
104
|
+
| `get_item` | `GET /items/{id}` | |
|
|
105
|
+
| `log_wear` | `POST /items/{id}/wear` | Defaults to today. |
|
|
106
|
+
| `log_wash` | `POST /items/{id}/wash` | Defaults to today. |
|
|
107
|
+
| `suggest_outfit` | `POST /outfits/suggest` | Rate limited to about 10 per minute per user. |
|
|
108
|
+
| `accept_outfit` | `POST /outfits/{id}/accept` | |
|
|
109
|
+
| `reject_outfit` | `POST /outfits/{id}/reject` | |
|
|
110
|
+
| `upload_photo` | `POST /uploads` (in-process) | Takes a small photo as base64 (up to 300 KB) and returns an `upload_id`. |
|
|
111
|
+
| `add_item` | `POST /items` | Takes an `upload_id` from `upload_photo` or `/uploads`. Wardrowbe detects the type unless you pass one. |
|
|
112
|
+
| `get_analytics` | `GET /analytics` | `days` from 7 to 365. |
|
|
113
|
+
| `get_wardrobe_summary` | `GET /analytics` | Counts, insights, most and never worn items. Good first call. |
|
|
114
|
+
| `get_most_worn_items` | `GET /analytics` | Up to 5 items, from the same trend window. |
|
|
115
|
+
| `get_items_to_wash` | `GET /items?needs_wash=true` | Items worn since their last wash. |
|
|
116
|
+
| `archive_item` | `POST /items/{id}/archive` | Hides an item from suggestions. Reversible. Takes an optional `reason`. |
|
|
117
|
+
| `restore_item` | `POST /items/{id}/restore` | Brings an archived item back. |
|
|
118
|
+
|
|
119
|
+
## Skill
|
|
120
|
+
|
|
121
|
+
The server publishes `skill://wardrowbe-skill/SKILL.md` as an MCP resource. It explains which tool to use for each task, how to add an item from a photo (including re-encoding large photos), and how archiving works. Clients that install skills pick it up automatically. The source is in [`skill/SKILL.md`](skill/SKILL.md).
|
|
122
|
+
|
|
123
|
+
## Development
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
npm install
|
|
127
|
+
npm run build
|
|
128
|
+
npm test
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Written against Wardrowbe 1.13.x. If Wardrowbe changes its endpoints, update `src/tools.ts`.
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { ConfigError, loadConfig } from "./config.js";
|
|
5
|
+
import { createMcpHttpServer } from "./http.js";
|
|
6
|
+
import { runLogin } from "./login.js";
|
|
7
|
+
import { createServer, SERVER_NAME, SERVER_VERSION } from "./server.js";
|
|
8
|
+
const USAGE = `Usage:
|
|
9
|
+
wardrowbe-mcp Run the MCP server (stdio, or http if MCP_TRANSPORT=http)
|
|
10
|
+
wardrowbe-mcp login [options] One-time sign-in. Prints a refresh token to stdout.
|
|
11
|
+
|
|
12
|
+
Login options (each can also come from the environment):
|
|
13
|
+
--issuer <url> OIDC issuer, e.g. https://pocket.example.com (OIDC_ISSUER_URL)
|
|
14
|
+
--client-id <id> OIDC client ID (OIDC_CLIENT_ID)
|
|
15
|
+
--client-secret <s> Only for confidential clients (OIDC_CLIENT_SECRET)
|
|
16
|
+
--port <n> Localhost port for the redirect. Default 8765.
|
|
17
|
+
`;
|
|
18
|
+
async function login(argv) {
|
|
19
|
+
const { values } = parseArgs({
|
|
20
|
+
args: argv,
|
|
21
|
+
options: {
|
|
22
|
+
issuer: { type: "string" },
|
|
23
|
+
"client-id": { type: "string" },
|
|
24
|
+
"client-secret": { type: "string" },
|
|
25
|
+
port: { type: "string" },
|
|
26
|
+
help: { type: "boolean", short: "h" },
|
|
27
|
+
},
|
|
28
|
+
strict: true,
|
|
29
|
+
});
|
|
30
|
+
if (values.help) {
|
|
31
|
+
process.stderr.write(USAGE);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const issuer = values.issuer ?? process.env.OIDC_ISSUER_URL;
|
|
35
|
+
const clientId = values["client-id"] ?? process.env.OIDC_CLIENT_ID;
|
|
36
|
+
const clientSecret = values["client-secret"] ?? process.env.OIDC_CLIENT_SECRET;
|
|
37
|
+
if (!issuer || !clientId) {
|
|
38
|
+
throw new ConfigError("login needs --issuer and --client-id (or OIDC_ISSUER_URL and OIDC_CLIENT_ID)");
|
|
39
|
+
}
|
|
40
|
+
const port = Number(values.port ?? "8765");
|
|
41
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
42
|
+
throw new ConfigError(`--port must be a port number, got "${values.port}"`);
|
|
43
|
+
}
|
|
44
|
+
const result = await runLogin({ issuerUrl: issuer, clientId, clientSecret, port });
|
|
45
|
+
// The token goes to stdout alone, so `wardrowbe-mcp login > token.txt` captures just the value.
|
|
46
|
+
process.stdout.write(`${result.refreshToken}\n`);
|
|
47
|
+
process.stderr.write([
|
|
48
|
+
"",
|
|
49
|
+
"Refresh token printed to stdout. Store it as a secret, not in the repo.",
|
|
50
|
+
"Set these for the MCP server:",
|
|
51
|
+
` OIDC_ISSUER_URL=${issuer}`,
|
|
52
|
+
` OIDC_CLIENT_ID=${clientId}`,
|
|
53
|
+
" OIDC_REFRESH_TOKEN=<the value above>",
|
|
54
|
+
"",
|
|
55
|
+
].join("\n"));
|
|
56
|
+
}
|
|
57
|
+
async function serve() {
|
|
58
|
+
const config = loadConfig(process.env);
|
|
59
|
+
if (config.transport === "http") {
|
|
60
|
+
const httpServer = createMcpHttpServer(config);
|
|
61
|
+
httpServer.listen(config.port, config.host, () => {
|
|
62
|
+
console.error(`${SERVER_NAME} ${SERVER_VERSION} listening on http://${config.host}:${config.port}/mcp`);
|
|
63
|
+
});
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
// stdio: stdout carries MCP frames, so diagnostics go to stderr only.
|
|
67
|
+
const server = createServer(config);
|
|
68
|
+
await server.connect(new StdioServerTransport());
|
|
69
|
+
console.error(`${SERVER_NAME} ${SERVER_VERSION} running on stdio`);
|
|
70
|
+
}
|
|
71
|
+
async function main() {
|
|
72
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
73
|
+
if (command === "login") {
|
|
74
|
+
await login(rest);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (command === "--help" || command === "-h") {
|
|
78
|
+
process.stderr.write(USAGE);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
await serve();
|
|
82
|
+
}
|
|
83
|
+
main().catch((err) => {
|
|
84
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
85
|
+
console.error(`${SERVER_NAME}: ${message}`);
|
|
86
|
+
process.exit(err instanceof ConfigError ? 2 : 1);
|
|
87
|
+
});
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Config } from "./config.js";
|
|
2
|
+
import type { TokenStore } from "./token-store.js";
|
|
3
|
+
export type FetchFn = typeof fetch;
|
|
4
|
+
/** How the OIDC path gets a refresh token when it has none: from disk, or from a browser sign-in. */
|
|
5
|
+
export interface SignInHooks {
|
|
6
|
+
store?: TokenStore;
|
|
7
|
+
/** Runs the browser sign-in and resolves with a refresh token. */
|
|
8
|
+
signIn?: () => Promise<string>;
|
|
9
|
+
}
|
|
10
|
+
export declare class WardrowbeApiError extends Error {
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly detail: string;
|
|
13
|
+
constructor(status: number, detail: string);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Provides a Wardrowbe access token. With a static token it returns that. With OIDC it
|
|
17
|
+
* exchanges the refresh token for an id token, then trades that id token at /auth/sync for
|
|
18
|
+
* a Wardrowbe access token, caching the result until shortly before it expires.
|
|
19
|
+
*/
|
|
20
|
+
export declare class TokenProvider {
|
|
21
|
+
private readonly config;
|
|
22
|
+
private readonly fetchFn;
|
|
23
|
+
private readonly now;
|
|
24
|
+
private readonly hooks;
|
|
25
|
+
private accessToken?;
|
|
26
|
+
private expiresAt;
|
|
27
|
+
private refreshToken?;
|
|
28
|
+
private inflight?;
|
|
29
|
+
constructor(config: Config, fetchFn?: FetchFn, now?: () => number, hooks?: SignInHooks);
|
|
30
|
+
getToken(): Promise<string>;
|
|
31
|
+
private exchange;
|
|
32
|
+
private refreshIdToken;
|
|
33
|
+
/** Current refresh token: the in-memory one, then the stored one, then a fresh browser sign-in. */
|
|
34
|
+
private currentRefreshToken;
|
|
35
|
+
/** Runs the browser sign-in and keeps the resulting refresh token. */
|
|
36
|
+
private signIn;
|
|
37
|
+
private refresh;
|
|
38
|
+
/** Keeps a refresh token in memory and in the store. A failed write is logged, not fatal. */
|
|
39
|
+
private remember;
|
|
40
|
+
}
|
|
41
|
+
/** Thin JSON client for the Wardrowbe REST API. */
|
|
42
|
+
export declare class WardrowbeClient {
|
|
43
|
+
private readonly config;
|
|
44
|
+
private readonly tokens;
|
|
45
|
+
private readonly fetchFn;
|
|
46
|
+
constructor(config: Config, tokens: TokenProvider, fetchFn?: FetchFn);
|
|
47
|
+
get<T>(path: string, query?: Record<string, string | number | boolean | undefined>): Promise<T>;
|
|
48
|
+
post<T>(path: string, body?: unknown): Promise<T>;
|
|
49
|
+
/** Sends a multipart form, such as an item with its photo. The boundary header is set by fetch. */
|
|
50
|
+
postForm<T>(path: string, form: FormData): Promise<T>;
|
|
51
|
+
private request;
|
|
52
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
export class WardrowbeApiError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
detail;
|
|
4
|
+
constructor(status, detail) {
|
|
5
|
+
super(`Wardrowbe API ${status}: ${detail}`);
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.detail = detail;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Refresh this long before the access token expires, so a call never starts with a dead token. */
|
|
11
|
+
const EXPIRY_MARGIN_MS = 60_000;
|
|
12
|
+
/** Used when an access token has no exp claim. */
|
|
13
|
+
const FALLBACK_TTL_MS = 5 * 60_000;
|
|
14
|
+
/**
|
|
15
|
+
* Provides a Wardrowbe access token. With a static token it returns that. With OIDC it
|
|
16
|
+
* exchanges the refresh token for an id token, then trades that id token at /auth/sync for
|
|
17
|
+
* a Wardrowbe access token, caching the result until shortly before it expires.
|
|
18
|
+
*/
|
|
19
|
+
export class TokenProvider {
|
|
20
|
+
config;
|
|
21
|
+
fetchFn;
|
|
22
|
+
now;
|
|
23
|
+
hooks;
|
|
24
|
+
accessToken;
|
|
25
|
+
expiresAt = 0;
|
|
26
|
+
refreshToken;
|
|
27
|
+
inflight;
|
|
28
|
+
constructor(config, fetchFn = fetch, now = Date.now, hooks = {}) {
|
|
29
|
+
this.config = config;
|
|
30
|
+
this.fetchFn = fetchFn;
|
|
31
|
+
this.now = now;
|
|
32
|
+
this.hooks = hooks;
|
|
33
|
+
this.refreshToken = config.oidc?.refreshToken;
|
|
34
|
+
}
|
|
35
|
+
async getToken() {
|
|
36
|
+
if (this.config.staticToken)
|
|
37
|
+
return this.config.staticToken;
|
|
38
|
+
if (this.accessToken && this.now() < this.expiresAt - EXPIRY_MARGIN_MS) {
|
|
39
|
+
return this.accessToken;
|
|
40
|
+
}
|
|
41
|
+
// Share one in-flight exchange so concurrent tool calls don't each refresh the token.
|
|
42
|
+
this.inflight ??= this.exchange().finally(() => {
|
|
43
|
+
this.inflight = undefined;
|
|
44
|
+
});
|
|
45
|
+
return this.inflight;
|
|
46
|
+
}
|
|
47
|
+
async exchange() {
|
|
48
|
+
const oidc = this.config.oidc;
|
|
49
|
+
if (!oidc)
|
|
50
|
+
throw new Error("No OIDC configuration");
|
|
51
|
+
const idToken = await this.refreshIdToken(oidc);
|
|
52
|
+
const res = await this.fetchFn(`${this.config.wardrowbeUrl}/api/v1/auth/sync`, {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
55
|
+
body: JSON.stringify({ id_token: idToken }),
|
|
56
|
+
});
|
|
57
|
+
const body = (await parseJson(res));
|
|
58
|
+
if (!res.ok || !body?.access_token) {
|
|
59
|
+
throw new WardrowbeApiError(res.status, `auth/sync failed: ${describe(body, res)}`);
|
|
60
|
+
}
|
|
61
|
+
this.accessToken = body.access_token;
|
|
62
|
+
const ttl = jwtTtlMs(body.access_token, this.now);
|
|
63
|
+
this.expiresAt = this.now() + (ttl ?? FALLBACK_TTL_MS);
|
|
64
|
+
return this.accessToken;
|
|
65
|
+
}
|
|
66
|
+
async refreshIdToken(oidc) {
|
|
67
|
+
const discovery = await this.fetchFn(`${oidc.issuerUrl}/.well-known/openid-configuration`, {
|
|
68
|
+
headers: { Accept: "application/json" },
|
|
69
|
+
});
|
|
70
|
+
const meta = (await parseJson(discovery));
|
|
71
|
+
if (!discovery.ok || !meta?.token_endpoint) {
|
|
72
|
+
throw new Error(`OIDC discovery failed at ${oidc.issuerUrl} (HTTP ${discovery.status})`);
|
|
73
|
+
}
|
|
74
|
+
const first = await this.refresh(meta.token_endpoint, oidc, await this.currentRefreshToken(oidc));
|
|
75
|
+
if (first.ok)
|
|
76
|
+
return first.idToken;
|
|
77
|
+
// The issuer rejected the token, so it has expired or been revoked. Sign in again once.
|
|
78
|
+
// Server errors are not a sign of a bad token, so they are reported as they are.
|
|
79
|
+
const rejected = first.status === 400 || first.status === 401;
|
|
80
|
+
if (!rejected || !this.hooks.signIn) {
|
|
81
|
+
throw new Error(`OIDC refresh failed (HTTP ${first.status}). The refresh token may be expired or revoked.`);
|
|
82
|
+
}
|
|
83
|
+
const second = await this.refresh(meta.token_endpoint, oidc, await this.signIn(oidc));
|
|
84
|
+
if (second.ok)
|
|
85
|
+
return second.idToken;
|
|
86
|
+
throw new Error(`OIDC refresh failed after signing in again (HTTP ${second.status}).`);
|
|
87
|
+
}
|
|
88
|
+
/** Current refresh token: the in-memory one, then the stored one, then a fresh browser sign-in. */
|
|
89
|
+
async currentRefreshToken(oidc) {
|
|
90
|
+
if (this.refreshToken)
|
|
91
|
+
return this.refreshToken;
|
|
92
|
+
const stored = await this.hooks.store?.load(oidc.issuerUrl, oidc.clientId);
|
|
93
|
+
if (stored) {
|
|
94
|
+
this.refreshToken = stored;
|
|
95
|
+
return stored;
|
|
96
|
+
}
|
|
97
|
+
return this.signIn(oidc);
|
|
98
|
+
}
|
|
99
|
+
/** Runs the browser sign-in and keeps the resulting refresh token. */
|
|
100
|
+
async signIn(oidc) {
|
|
101
|
+
if (!this.hooks.signIn) {
|
|
102
|
+
throw new Error("No refresh token is available. Set OIDC_REFRESH_TOKEN, or run `wardrowbe-mcp login`.");
|
|
103
|
+
}
|
|
104
|
+
const token = await this.hooks.signIn();
|
|
105
|
+
await this.remember(oidc, token);
|
|
106
|
+
return token;
|
|
107
|
+
}
|
|
108
|
+
async refresh(tokenEndpoint, oidc, refreshToken) {
|
|
109
|
+
const form = new URLSearchParams({
|
|
110
|
+
grant_type: "refresh_token",
|
|
111
|
+
refresh_token: refreshToken,
|
|
112
|
+
client_id: oidc.clientId,
|
|
113
|
+
});
|
|
114
|
+
if (oidc.clientSecret)
|
|
115
|
+
form.set("client_secret", oidc.clientSecret);
|
|
116
|
+
const res = await this.fetchFn(tokenEndpoint, {
|
|
117
|
+
method: "POST",
|
|
118
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
119
|
+
body: form,
|
|
120
|
+
});
|
|
121
|
+
const tokens = (await parseJson(res));
|
|
122
|
+
if (!res.ok || !tokens?.id_token)
|
|
123
|
+
return { ok: false, status: res.status };
|
|
124
|
+
// Some issuers rotate refresh tokens. Keep the newest one so the next run can use it.
|
|
125
|
+
if (tokens.refresh_token)
|
|
126
|
+
await this.remember(oidc, tokens.refresh_token);
|
|
127
|
+
return { ok: true, idToken: tokens.id_token };
|
|
128
|
+
}
|
|
129
|
+
/** Keeps a refresh token in memory and in the store. A failed write is logged, not fatal. */
|
|
130
|
+
async remember(oidc, refreshToken) {
|
|
131
|
+
this.refreshToken = refreshToken;
|
|
132
|
+
const store = this.hooks.store;
|
|
133
|
+
if (!store)
|
|
134
|
+
return;
|
|
135
|
+
try {
|
|
136
|
+
await store.save({ issuerUrl: oidc.issuerUrl, clientId: oidc.clientId, refreshToken });
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
140
|
+
console.error(`wardrowbe-mcp: could not save the refresh token to ${store.path}: ${message}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** Thin JSON client for the Wardrowbe REST API. */
|
|
145
|
+
export class WardrowbeClient {
|
|
146
|
+
config;
|
|
147
|
+
tokens;
|
|
148
|
+
fetchFn;
|
|
149
|
+
constructor(config, tokens, fetchFn = fetch) {
|
|
150
|
+
this.config = config;
|
|
151
|
+
this.tokens = tokens;
|
|
152
|
+
this.fetchFn = fetchFn;
|
|
153
|
+
}
|
|
154
|
+
get(path, query) {
|
|
155
|
+
return this.request("GET", path, { query });
|
|
156
|
+
}
|
|
157
|
+
post(path, body) {
|
|
158
|
+
return this.request("POST", path, { body });
|
|
159
|
+
}
|
|
160
|
+
/** Sends a multipart form, such as an item with its photo. The boundary header is set by fetch. */
|
|
161
|
+
postForm(path, form) {
|
|
162
|
+
return this.request("POST", path, { form });
|
|
163
|
+
}
|
|
164
|
+
async request(method, path, opts) {
|
|
165
|
+
const url = new URL(`${this.config.wardrowbeUrl}/api/v1${path}`);
|
|
166
|
+
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
|
167
|
+
if (v !== undefined)
|
|
168
|
+
url.searchParams.set(k, String(v));
|
|
169
|
+
}
|
|
170
|
+
const token = await this.tokens.getToken();
|
|
171
|
+
const headers = {
|
|
172
|
+
Authorization: `Bearer ${token}`,
|
|
173
|
+
Accept: "application/json",
|
|
174
|
+
};
|
|
175
|
+
const init = { method, headers };
|
|
176
|
+
if (opts.form) {
|
|
177
|
+
init.body = opts.form;
|
|
178
|
+
}
|
|
179
|
+
else if (opts.body !== undefined) {
|
|
180
|
+
headers["Content-Type"] = "application/json";
|
|
181
|
+
init.body = JSON.stringify(opts.body);
|
|
182
|
+
}
|
|
183
|
+
const res = await this.fetchFn(url, init);
|
|
184
|
+
const body = await parseJson(res);
|
|
185
|
+
if (!res.ok)
|
|
186
|
+
throw new WardrowbeApiError(res.status, describe(body, res));
|
|
187
|
+
return body;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async function parseJson(res) {
|
|
191
|
+
const text = await res.text();
|
|
192
|
+
if (!text)
|
|
193
|
+
return undefined;
|
|
194
|
+
try {
|
|
195
|
+
return JSON.parse(text);
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function describe(body, res) {
|
|
202
|
+
const detail = body?.detail;
|
|
203
|
+
if (typeof detail === "string")
|
|
204
|
+
return detail;
|
|
205
|
+
if (detail !== undefined)
|
|
206
|
+
return JSON.stringify(detail).slice(0, 300);
|
|
207
|
+
return res.statusText || "request failed";
|
|
208
|
+
}
|
|
209
|
+
/** Milliseconds until a JWT's exp claim, or undefined when it has none. Signature is not checked. */
|
|
210
|
+
function jwtTtlMs(jwt, now) {
|
|
211
|
+
const payload = jwt.split(".")[1];
|
|
212
|
+
if (!payload)
|
|
213
|
+
return undefined;
|
|
214
|
+
try {
|
|
215
|
+
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
216
|
+
return typeof claims.exp === "number" ? claims.exp * 1000 - now() : undefined;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type Transport = "stdio" | "http";
|
|
2
|
+
export interface Config {
|
|
3
|
+
wardrowbeUrl: string;
|
|
4
|
+
/** Static access token for the Wardrowbe API (JWT). Optional when OIDC is configured. */
|
|
5
|
+
staticToken?: string;
|
|
6
|
+
oidc?: {
|
|
7
|
+
issuerUrl: string;
|
|
8
|
+
clientId: string;
|
|
9
|
+
clientSecret?: string;
|
|
10
|
+
/** Explicit refresh token. When absent, the stored one is used, or the browser sign-in runs. */
|
|
11
|
+
refreshToken?: string;
|
|
12
|
+
};
|
|
13
|
+
/** Where the refresh token is kept between runs. Set only when OIDC is configured. */
|
|
14
|
+
tokenFile?: string;
|
|
15
|
+
transport: Transport;
|
|
16
|
+
host: string;
|
|
17
|
+
port: number;
|
|
18
|
+
/** Required for the http transport. Clients send it as a Bearer token. */
|
|
19
|
+
apiKey?: string;
|
|
20
|
+
}
|
|
21
|
+
export declare class ConfigError extends Error {
|
|
22
|
+
}
|
|
23
|
+
/** Parses config from environment variables. Pure, so it is easy to test. */
|
|
24
|
+
export declare function loadConfig(env: NodeJS.ProcessEnv): Config;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { defaultTokenFile } from "./token-store.js";
|
|
2
|
+
export class ConfigError extends Error {
|
|
3
|
+
}
|
|
4
|
+
/** Parses config from environment variables. Pure, so it is easy to test. */
|
|
5
|
+
export function loadConfig(env) {
|
|
6
|
+
const wardrowbeUrl = (env.WARDROWBE_URL ?? "").trim().replace(/\/+$/, "");
|
|
7
|
+
if (!wardrowbeUrl) {
|
|
8
|
+
throw new ConfigError("WARDROWBE_URL is required (e.g. https://wardrowbe.example.com)");
|
|
9
|
+
}
|
|
10
|
+
try {
|
|
11
|
+
new URL(wardrowbeUrl);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new ConfigError(`WARDROWBE_URL is not a valid URL: ${wardrowbeUrl}`);
|
|
15
|
+
}
|
|
16
|
+
const staticToken = env.WARDROWBE_TOKEN?.trim() || undefined;
|
|
17
|
+
const oidcIssuer = env.OIDC_ISSUER_URL?.trim();
|
|
18
|
+
const oidcClient = env.OIDC_CLIENT_ID?.trim();
|
|
19
|
+
// OIDC_REFRESH_TOKEN is optional. Without it, the server signs in through the browser and stores the result.
|
|
20
|
+
const oidcRefresh = env.OIDC_REFRESH_TOKEN?.trim() || undefined;
|
|
21
|
+
let oidc;
|
|
22
|
+
let tokenFile;
|
|
23
|
+
if (oidcIssuer || oidcClient || oidcRefresh) {
|
|
24
|
+
if (!oidcIssuer || !oidcClient) {
|
|
25
|
+
throw new ConfigError("OIDC needs OIDC_ISSUER_URL and OIDC_CLIENT_ID");
|
|
26
|
+
}
|
|
27
|
+
oidc = {
|
|
28
|
+
issuerUrl: oidcIssuer.replace(/\/+$/, ""),
|
|
29
|
+
clientId: oidcClient,
|
|
30
|
+
clientSecret: env.OIDC_CLIENT_SECRET?.trim() || undefined,
|
|
31
|
+
refreshToken: oidcRefresh,
|
|
32
|
+
};
|
|
33
|
+
tokenFile = env.WARDROWBE_TOKEN_FILE?.trim() || defaultTokenFile(env);
|
|
34
|
+
}
|
|
35
|
+
if (!staticToken && !oidc) {
|
|
36
|
+
throw new ConfigError("Set WARDROWBE_TOKEN, or OIDC_ISSUER_URL and OIDC_CLIENT_ID to sign in with your identity provider");
|
|
37
|
+
}
|
|
38
|
+
const transport = (env.MCP_TRANSPORT?.trim() || "stdio");
|
|
39
|
+
if (transport !== "stdio" && transport !== "http") {
|
|
40
|
+
throw new ConfigError(`MCP_TRANSPORT must be "stdio" or "http", got "${transport}"`);
|
|
41
|
+
}
|
|
42
|
+
const port = Number(env.MCP_PORT ?? "8080");
|
|
43
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
44
|
+
throw new ConfigError(`MCP_PORT must be a port number, got "${env.MCP_PORT}"`);
|
|
45
|
+
}
|
|
46
|
+
const apiKey = env.MCP_API_KEY?.trim() || undefined;
|
|
47
|
+
if (transport === "http" && !apiKey) {
|
|
48
|
+
throw new ConfigError("MCP_API_KEY is required for the http transport");
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
wardrowbeUrl,
|
|
52
|
+
staticToken,
|
|
53
|
+
oidc,
|
|
54
|
+
tokenFile,
|
|
55
|
+
transport,
|
|
56
|
+
// Bind to loopback unless the caller opts in. Container deployments set MCP_BIND_HOST=0.0.0.0.
|
|
57
|
+
host: env.MCP_BIND_HOST?.trim() || "127.0.0.1",
|
|
58
|
+
port,
|
|
59
|
+
apiKey,
|
|
60
|
+
};
|
|
61
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
+
import type { Config } from "./config.js";
|
|
3
|
+
import { type UploadStore } from "./uploads.js";
|
|
4
|
+
/** Constant-time check of the Bearer token, so the comparison doesn't leak the key by timing. */
|
|
5
|
+
export declare function isAuthorized(header: string | undefined, apiKey: string): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Serves the MCP endpoint at /mcp over Streamable HTTP, stateless, behind a Bearer API key.
|
|
8
|
+
* Also serves POST /uploads, where the app sends a photo before asking the agent to add it.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createMcpHttpServer(config: Config, uploads?: UploadStore): import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
|