@plaud-ai/mcp 0.2.3 → 0.3.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.
@@ -1,352 +0,0 @@
1
- // ../shared/dist/oauth.js
2
- import { randomBytes, createHash } from "crypto";
3
-
4
- // ../shared/dist/token-store.js
5
- import { readFile, writeFile, mkdir, rm } from "fs/promises";
6
- import { join } from "path";
7
- import { homedir } from "os";
8
- var TokenStore = class {
9
- configDir;
10
- tokenPath;
11
- constructor(filename = "tokens.json") {
12
- this.configDir = join(homedir(), ".plaud");
13
- this.tokenPath = join(this.configDir, filename);
14
- }
15
- async save(tokenSet) {
16
- await mkdir(this.configDir, { recursive: true });
17
- await writeFile(this.tokenPath, JSON.stringify(tokenSet, null, 2), "utf-8");
18
- }
19
- async load() {
20
- try {
21
- const data = await readFile(this.tokenPath, "utf-8");
22
- return JSON.parse(data);
23
- } catch {
24
- return null;
25
- }
26
- }
27
- async clear() {
28
- try {
29
- await rm(this.tokenPath);
30
- } catch {
31
- }
32
- }
33
- };
34
-
35
- // ../shared/dist/oauth.js
36
- var DEFAULT_AUTHORIZATION_URL = "https://web.plaud.ai/platform/oauth";
37
- var DEFAULT_TOKEN_URL = "https://platform.plaud.ai/developer/api/oauth/third-party/access-token";
38
- var DEFAULT_REFRESH_URL = "https://platform.plaud.ai/developer/api/oauth/third-party/access-token/refresh";
39
- function generateCodeVerifier() {
40
- return randomBytes(32).toString("base64url");
41
- }
42
- function generateCodeChallenge(verifier) {
43
- return createHash("sha256").update(verifier).digest("base64url");
44
- }
45
- function generateState() {
46
- return randomBytes(16).toString("base64url");
47
- }
48
- var OAuth = class {
49
- config;
50
- tokenStore;
51
- authorizationUrl;
52
- tokenUrl;
53
- refreshUrl;
54
- constructor(config) {
55
- this.config = config;
56
- this.tokenStore = new TokenStore(config.tokenFile);
57
- this.authorizationUrl = config.authorizationUrl ?? DEFAULT_AUTHORIZATION_URL;
58
- this.tokenUrl = config.tokenUrl ?? DEFAULT_TOKEN_URL;
59
- this.refreshUrl = config.refreshUrl ?? DEFAULT_REFRESH_URL;
60
- }
61
- createAuthorizationRequest() {
62
- const codeVerifier = generateCodeVerifier();
63
- const codeChallenge = generateCodeChallenge(codeVerifier);
64
- const state = generateState();
65
- const params = new URLSearchParams({
66
- client_id: this.config.clientId,
67
- redirect_uri: this.config.redirectUri,
68
- response_type: "code",
69
- code_challenge: codeChallenge,
70
- code_challenge_method: "S256",
71
- state
72
- });
73
- return {
74
- url: `${this.authorizationUrl}?${params.toString()}`,
75
- codeVerifier,
76
- state
77
- };
78
- }
79
- /**
80
- * @deprecated Use createAuthorizationRequest() for PKCE flow
81
- */
82
- getAuthorizationUrl() {
83
- return this.createAuthorizationRequest().url;
84
- }
85
- async exchangeCode(code, codeVerifier, state) {
86
- const basicAuth = Buffer.from(`${this.config.clientId}:${this.config.clientSecret}`).toString("base64");
87
- const body = {
88
- code,
89
- redirect_uri: this.config.redirectUri
90
- };
91
- if (codeVerifier) {
92
- body.code_verifier = codeVerifier;
93
- }
94
- if (state) {
95
- body.state = state;
96
- }
97
- const res = await fetch(this.tokenUrl, {
98
- method: "POST",
99
- headers: {
100
- "Content-Type": "application/x-www-form-urlencoded",
101
- Accept: "application/json",
102
- Authorization: `Basic ${basicAuth}`,
103
- ...this.config.extraHeaders
104
- },
105
- body: new URLSearchParams(body)
106
- });
107
- if (!res.ok) {
108
- throw new Error(`Token exchange failed: ${res.status} ${await res.text()}`);
109
- }
110
- const data = await res.json();
111
- const tokenSet = {
112
- access_token: data.access_token,
113
- refresh_token: data.refresh_token,
114
- token_type: data.token_type ?? "Bearer",
115
- expires_at: data.expires_in ? Date.now() + data.expires_in * 1e3 : void 0
116
- };
117
- await this.tokenStore.save(tokenSet);
118
- return tokenSet;
119
- }
120
- async getAccessToken() {
121
- const tokenSet = await this.tokenStore.load();
122
- if (!tokenSet)
123
- return null;
124
- if (tokenSet.expires_at && Date.now() > tokenSet.expires_at - 6e4) {
125
- if (tokenSet.refresh_token) {
126
- try {
127
- const refreshed = await this.refresh(tokenSet.refresh_token);
128
- return refreshed.access_token;
129
- } catch {
130
- return null;
131
- }
132
- }
133
- return null;
134
- }
135
- return tokenSet.access_token;
136
- }
137
- async refresh(refreshToken) {
138
- const res = await fetch(this.refreshUrl, {
139
- method: "POST",
140
- headers: {
141
- "Content-Type": "application/x-www-form-urlencoded",
142
- Accept: "application/json",
143
- ...this.config.extraHeaders
144
- },
145
- body: new URLSearchParams({
146
- refresh_token: refreshToken
147
- })
148
- });
149
- if (!res.ok) {
150
- const body = await res.text();
151
- throw new Error(`Token refresh failed: ${res.status} ${body}`);
152
- }
153
- const data = await res.json();
154
- const tokenSet = {
155
- access_token: data.access_token,
156
- refresh_token: data.refresh_token ?? refreshToken,
157
- token_type: data.token_type ?? "Bearer",
158
- expires_at: data.expires_in ? Date.now() + data.expires_in * 1e3 : void 0
159
- };
160
- await this.tokenStore.save(tokenSet);
161
- return tokenSet;
162
- }
163
- async logout() {
164
- await this.tokenStore.clear();
165
- }
166
- };
167
-
168
- // ../shared/dist/client.js
169
- var DEFAULT_API_BASE = "https://platform.plaud.ai/developer/api";
170
- var PlaudClient = class {
171
- oauth;
172
- apiBase;
173
- extraHeaders;
174
- staticToken;
175
- constructor(config) {
176
- this.oauth = new OAuth(config);
177
- this.apiBase = config.apiBase ?? DEFAULT_API_BASE;
178
- this.extraHeaders = config.extraHeaders ?? {};
179
- this.staticToken = config.staticToken;
180
- }
181
- get auth() {
182
- return this.oauth;
183
- }
184
- async request(path, init) {
185
- const token = this.staticToken ?? await this.oauth.getAccessToken();
186
- if (!token) {
187
- throw new Error("Not authenticated. Please login first.");
188
- }
189
- const url = `${this.apiBase}${path}`;
190
- const method = init?.method ?? "GET";
191
- const headers = {
192
- Authorization: `Bearer ${token}`,
193
- Accept: "application/json",
194
- ...this.extraHeaders,
195
- ...init?.headers
196
- };
197
- const res = await fetch(url, { ...init, headers });
198
- if (!res.ok) {
199
- const body = await res.text();
200
- if (res.status === 422) {
201
- try {
202
- const parsed = JSON.parse(body);
203
- const messages = parsed.detail.map((d) => `${d.loc.at(-1)}: ${d.msg}`).join("; ");
204
- throw new Error(messages);
205
- } catch (e) {
206
- if (e instanceof SyntaxError)
207
- throw new Error(`API error: ${res.status} ${res.statusText}`);
208
- throw e;
209
- }
210
- }
211
- throw new Error(`API error: ${res.status} ${res.statusText}`);
212
- }
213
- const json = await res.json();
214
- return json;
215
- }
216
- async getCurrentUser() {
217
- return this.request("/open/third-party/users/current");
218
- }
219
- async revokeCurrentUser() {
220
- await this.request("/open/third-party/users/current/revoke", {
221
- method: "POST"
222
- });
223
- }
224
- async listFiles(page = 1, pageSize = 20) {
225
- return this.request(`/open/third-party/files/?page=${page}&page_size=${pageSize}`);
226
- }
227
- async getFile(fileId) {
228
- return this.request(`/open/third-party/files/${fileId}`);
229
- }
230
- };
231
-
232
- // ../shared/dist/oauth-callback-server.js
233
- import { createServer } from "http";
234
- var SUCCESS_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Plaud</title></head><body style="font-family:system-ui;padding:2rem;text-align:center;"><h1>Authorization successful!</h1><p>You can close this tab.</p></body></html>';
235
- var NEUTRAL_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Plaud</title></head><body style="font-family:system-ui;padding:2rem;text-align:center;"><h1>Continue authorization in the original window.</h1><p>This page can be closed.</p></body></html>';
236
- function errorHtml(message) {
237
- const escaped = message.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
238
- return '<!doctype html><html><head><meta charset="utf-8"><title>Plaud</title></head><body style="font-family:system-ui;padding:2rem;text-align:center;"><h1>Authorization failed</h1><pre style="white-space:pre-wrap;">' + escaped + "</pre></body></html>";
239
- }
240
- var CORS_HEADERS = {
241
- "Access-Control-Allow-Origin": "*",
242
- "Access-Control-Allow-Methods": "GET, OPTIONS",
243
- "Access-Control-Allow-Headers": "*"
244
- };
245
- function runOAuthCallback(opts) {
246
- const { port, expectedState, exchangeCode, timeoutMs = 12e4, onListening, postSuccessDelayMs = 1500 } = opts;
247
- return new Promise((resolve) => {
248
- let settled = false;
249
- let exchangeStarted = false;
250
- let exchangeSucceeded = false;
251
- let timeoutId = null;
252
- let closeTimeoutId = null;
253
- const server = createServer((req, res) => {
254
- if (req.method === "OPTIONS") {
255
- res.writeHead(204, CORS_HEADERS);
256
- res.end();
257
- return;
258
- }
259
- const reqUrl = new URL(req.url ?? "/", `http://localhost:${port}`);
260
- if (reqUrl.pathname !== "/auth/callback") {
261
- res.writeHead(404, CORS_HEADERS);
262
- res.end();
263
- return;
264
- }
265
- const params = reqUrl.searchParams;
266
- const error = params.get("error");
267
- const state = params.get("state");
268
- const code = params.get("code");
269
- if (error) {
270
- const desc = params.get("error_description") ?? error;
271
- res.writeHead(400, { "Content-Type": "text/html", ...CORS_HEADERS });
272
- res.end(errorHtml(`Authorization denied: ${desc}`));
273
- finalize({ status: "denied", error: new Error(desc) });
274
- return;
275
- }
276
- if (!state || state !== expectedState) {
277
- respondNeutral(res);
278
- return;
279
- }
280
- if (exchangeSucceeded) {
281
- respondSuccess(res);
282
- return;
283
- }
284
- if (!code) {
285
- respondNeutral(res);
286
- return;
287
- }
288
- if (exchangeStarted) {
289
- respondNeutral(res);
290
- return;
291
- }
292
- exchangeStarted = true;
293
- exchangeCode(code).then(() => {
294
- exchangeSucceeded = true;
295
- respondSuccess(res);
296
- finalize({ status: "success" });
297
- }, (err) => {
298
- const e = err instanceof Error ? err : new Error(String(err));
299
- res.writeHead(500, { "Content-Type": "text/html", ...CORS_HEADERS });
300
- res.end(errorHtml(e.message));
301
- finalize({ status: "exchange-failed", error: e });
302
- });
303
- });
304
- server.on("error", (err) => {
305
- if (settled)
306
- return;
307
- const message = err.code === "EADDRINUSE" ? `port ${port} is in use \u2014 another \`plaud login\` may still be running. Wait a few seconds and retry.` : `callback server error: ${err.message}`;
308
- finalize({ status: "listen-failed", error: new Error(message) }, true);
309
- });
310
- timeoutId = setTimeout(() => {
311
- finalize({ status: "timeout" }, true);
312
- }, timeoutMs);
313
- server.listen(port, () => {
314
- onListening?.();
315
- });
316
- function respondSuccess(res) {
317
- res.writeHead(200, { "Content-Type": "text/html", ...CORS_HEADERS });
318
- res.end(SUCCESS_HTML);
319
- }
320
- function respondNeutral(res) {
321
- res.writeHead(200, { "Content-Type": "text/html", ...CORS_HEADERS });
322
- res.end(NEUTRAL_HTML);
323
- }
324
- function finalize(result, immediate = false) {
325
- if (settled)
326
- return;
327
- settled = true;
328
- if (timeoutId) {
329
- clearTimeout(timeoutId);
330
- timeoutId = null;
331
- }
332
- const close = () => {
333
- try {
334
- server.closeAllConnections?.();
335
- } catch {
336
- }
337
- server.close(() => resolve(result));
338
- };
339
- if (immediate || result.status !== "success") {
340
- close();
341
- } else {
342
- closeTimeoutId = setTimeout(close, postSuccessDelayMs);
343
- closeTimeoutId.unref?.();
344
- }
345
- }
346
- });
347
- }
348
-
349
- export {
350
- PlaudClient,
351
- runOAuthCallback
352
- };
@@ -1,33 +0,0 @@
1
- import {
2
- PlaudClient
3
- } from "./chunk-3XRFIJUG.js";
4
-
5
- // src/config.ts
6
- function buildExtraHeaders() {
7
- const headers = {};
8
- if (process.env.PLAUD_ENV) headers["x-pld-env"] = process.env.PLAUD_ENV;
9
- if (process.env.PLAUD_REGION) headers["x-pld-region"] = process.env.PLAUD_REGION;
10
- return headers;
11
- }
12
- var CONFIG = {
13
- clientId: process.env.PLAUD_MCP_CLIENT_ID ?? process.env.PLAUD_CLIENT_ID ?? "client_9c501dad-8a0d-40b2-a7b0-d1cb8787f674",
14
- clientSecret: process.env.PLAUD_CLIENT_SECRET ?? "",
15
- redirectUri: "http://localhost:8199/auth/callback",
16
- tokenFile: "tokens-mcp.json",
17
- apiBase: process.env.PLAUD_API_BASE,
18
- authorizationUrl: process.env.PLAUD_AUTH_URL,
19
- tokenUrl: process.env.PLAUD_TOKEN_URL,
20
- refreshUrl: process.env.PLAUD_REFRESH_URL,
21
- extraHeaders: buildExtraHeaders()
22
- };
23
- var client = null;
24
- function getClient() {
25
- if (!client) {
26
- client = new PlaudClient(CONFIG);
27
- }
28
- return client;
29
- }
30
-
31
- export {
32
- getClient
33
- };