forked from nicobailon/pi-mcp-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth-handler.ts
More file actions
57 lines (50 loc) · 1.68 KB
/
oauth-handler.ts
File metadata and controls
57 lines (50 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// oauth-handler.ts - OAuth token management for MCP servers
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
// Token storage path for a server
function getTokensPath(serverName: string): string {
return join(homedir(), ".pi", "agent", "mcp-oauth", serverName, "tokens.json");
}
/**
* Get stored OAuth tokens for a server (if any).
* Returns undefined if no tokens or tokens are expired.
*
* Token file location: ~/.pi/agent/mcp-oauth/<server>/tokens.json
*
* Expected format:
* {
* "access_token": "...",
* "token_type": "bearer",
* "refresh_token": "...", // optional
* "expires_in": 3600, // optional, seconds
* "expiresAt": 1234567890 // optional, absolute timestamp ms
* }
*/
export function getStoredTokens(serverName: string): OAuthTokens | undefined {
const tokensPath = getTokensPath(serverName);
if (!existsSync(tokensPath)) return undefined;
try {
const stored = JSON.parse(readFileSync(tokensPath, "utf-8"));
// Validate required field
if (!stored.access_token || typeof stored.access_token !== "string") {
return undefined;
}
// Check expiration if expiresAt is set
if (stored.expiresAt && typeof stored.expiresAt === "number") {
if (Date.now() > stored.expiresAt) {
// Token expired
return undefined;
}
}
return {
access_token: stored.access_token,
token_type: stored.token_type ?? "bearer",
refresh_token: stored.refresh_token,
expires_in: stored.expires_in,
};
} catch {
return undefined;
}
}