-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.ts
More file actions
266 lines (242 loc) · 10 KB
/
Copy pathindex.ts
File metadata and controls
266 lines (242 loc) · 10 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#!/usr/bin/env node
import { isMainModule } from "./is-main-module.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { PerplexityClient } from "./client.js";
import { ensureDaemon, startDaemon } from "./daemon/launcher.js";
import { registerTools } from "./tools.js";
import { registerPrompts } from "./prompts.js";
import { registerResources } from "./resources.js";
import { loadToolConfig, getEnabledTools } from "./tool-config.js";
import { watchActiveProfile, watchReinit } from "./reinit-watcher.js";
import { getActiveName } from "./profiles.js";
import { getPackageVersion } from "./package-version.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore — vault.js is a plain JS module; types inferred at call-site.
import { getUnsealMaterial } from "./vault.js";
let client: PerplexityClient;
let clientInitPromise: Promise<void> | null = null;
async function getClient(): Promise<PerplexityClient> {
if (!clientInitPromise) clientInitPromise = client.init();
await clientInitPromise;
return client;
}
// Pre-flight runs at most once per server lifecycle; gate ensures repeated
// startups in tests / hot-reload paths don't spam the warning.
let _vaultPreflightDone = false;
export function __resetVaultPreflightForTests(): void {
_vaultPreflightDone = false;
}
/**
* Probe the vault unseal chain at startup. If unsealing succeeds, the result
* is cached inside `vault.js` for free — subsequent tool calls skip the
* keychain hit. If it fails (e.g. headless Codex CLI: no keychain, no env var,
* no TTY), emit a structured stderr warning so the user sees the actionable
* setup hint in their IDE's MCP server-launch logs instead of waiting for the
* first cookie-needing tool to fail with a deep-stack "Vault locked" trace.
*
* Never throws. The MCP server must continue to load and serve tools that
* don't need cookies (perplexity_doctor, anonymous perplexity_search).
*/
export async function runVaultPreflight(
stderr: NodeJS.WritableStream = process.stderr,
): Promise<void> {
if (_vaultPreflightDone) return;
_vaultPreflightDone = true;
try {
await getUnsealMaterial();
// Success: cache primed, no output.
} catch (err) {
const summary = err instanceof Error ? err.message.split("\n")[0] : String(err);
stderr.write(`[perplexity-mcp] WARN vault-locked: ${summary}\n`);
stderr.write(`[perplexity-mcp] Setup docs: docs/codex-cli-setup.md\n`);
stderr.write(`[perplexity-mcp] Tools that don't need cookies (perplexity_doctor, perplexity_search anonymous mode) will still work.\n`);
stderr.write(`[perplexity-mcp] Tools that need cookies (perplexity_research, perplexity_compute, perplexity_reason) will fail until the vault is unsealed.\n`);
}
}
export async function waitForStdioInputClose(
stdin: NodeJS.ReadableStream = process.stdin,
): Promise<void> {
stdin.resume();
await new Promise<void>((resolve) => {
const done = () => {
stdin.off("end", done);
stdin.off("close", done);
resolve();
};
stdin.once("end", done);
stdin.once("close", done);
});
}
const SHUTDOWN_TIMEOUT_MS = 5000;
// Race client.shutdown() against a timer so a wedged browser context (patchright
// hung on a frame, keytar deadlocked, etc.) can't pin the process forever. The
// timer is unref'd so it doesn't itself keep the loop alive after shutdown wins.
export async function shutdownClientWithTimeout(
c: { shutdown: () => Promise<void> } | undefined,
timeoutMs: number = SHUTDOWN_TIMEOUT_MS,
): Promise<void> {
if (!c) return;
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<void>((resolve) => {
timer = setTimeout(() => {
console.error(`[perplexity-mcp] WARN shutdown timeout after ${timeoutMs}ms — exiting.`);
resolve();
}, timeoutMs);
timer.unref?.();
});
try {
await Promise.race([c.shutdown().catch(() => undefined), timeout]);
} finally {
if (timer) clearTimeout(timer);
}
}
export async function main() {
client = new PerplexityClient();
const server = new McpServer({
name: "perplexity",
version: getPackageVersion(),
});
const toolConfig = loadToolConfig();
const enabledTools = getEnabledTools(toolConfig);
registerResources(server);
registerPrompts(server);
registerTools(server, getClient, enabledTools);
const profile = process.env.PERPLEXITY_PROFILE || getActiveName() || "default";
console.error(`[perplexity-mcp] Starting with profile: ${profile}`);
// Pre-flight the vault unseal chain BEFORE the stdio transport connects, so
// any "Vault locked" warning lands in the IDE's server-launch logs rather
// than surfacing later as a cryptic deep-stack error on the first cookie
// call. Never throws — the server still serves doctor + anonymous search.
await runVaultPreflight();
// Track the currently-watched profile so the active-pointer watcher can
// rebind the per-profile reinit watcher when the user switches accounts
// from the dashboard. Without this rebind the stdio server keeps watching
// the old profile's `.reinit` and silently misses login events on the new
// profile, leaving its in-memory browser context stuck on stale cookies.
let currentWatchedProfile = profile;
let watcher = watchReinit(currentWatchedProfile, async () => {
console.error("[perplexity-mcp] .reinit sentinel fired — reloading client.");
try {
clientInitPromise = client.reinit();
await clientInitPromise;
} catch (err) {
console.error("[perplexity-mcp] reinit failed:", err);
}
});
const activeWatcher = watchActiveProfile(undefined, async () => {
try {
const nextProfile = process.env.PERPLEXITY_PROFILE || getActiveName() || "default";
if (nextProfile !== currentWatchedProfile) {
console.error(`[perplexity-mcp] active profile changed: ${currentWatchedProfile} → ${nextProfile}; reloading client.`);
currentWatchedProfile = nextProfile;
watcher.dispose();
watcher = watchReinit(nextProfile, async () => {
console.error("[perplexity-mcp] .reinit sentinel fired — reloading client.");
try {
clientInitPromise = client.reinit();
await clientInitPromise;
} catch (err) {
console.error("[perplexity-mcp] reinit failed:", err);
}
});
}
clientInitPromise = client.reinit();
await clientInitPromise;
} catch (err) {
console.error("[perplexity-mcp] active-profile reload failed:", err);
}
});
const disposeWatchers = () => {
try { watcher.dispose(); } catch {}
try { activeWatcher.dispose(); } catch {}
};
process.on("SIGINT", async () => {
disposeWatchers();
await shutdownClientWithTimeout(client);
process.exit(0);
});
process.on("SIGTERM", async () => {
disposeWatchers();
await shutdownClientWithTimeout(client);
process.exit(0);
});
const transport = new StdioServerTransport();
await server.connect(transport);
try {
await waitForStdioInputClose();
} finally {
disposeWatchers();
await shutdownClientWithTimeout(client);
}
}
if (isMainModule(import.meta.url)) {
runEntrypoint().catch(async (error) => {
console.error("[perplexity-mcp] Fatal error:", error);
await shutdownClientWithTimeout(client);
process.exit(1);
});
}
async function runEntrypoint() {
if (process.argv.length > 2) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - cli.js is a plain JS module; types inferred at runtime.
const { parseArgs, routeCommand } = await import("./cli.js");
const result = await routeCommand(parseArgs(process.argv.slice(2)));
if (result.stdout) {
process.stdout.write(result.stdout);
}
if (result.stderr) {
process.stderr.write(result.stderr);
}
process.exitCode = result.code;
return;
}
await main();
}
// Re-export public API for library consumers
export { PerplexityClient } from "./client.js";
export { ensureDaemon, startDaemon } from "./daemon/launcher.js";
export { attachToDaemon } from "./daemon/attach.js";
export { registerTools } from "./tools.js";
export { registerPrompts } from "./prompts.js";
export { registerResources } from "./resources.js";
export { formatResponse, buildHistoryBody, buildHistoryEntry, buildStoredHistoryEntry, buildAnswerPreview } from "./format.js";
export {
append as appendHistory,
countAll as countAllHistory,
deleteEntry,
findPendingByThread,
get,
getAttachmentsDir,
getAttachmentsRoot,
getHistoryDir,
getIndexPath as getHistoryPath,
getMdPath,
list as readHistory,
pin,
rebuildIndex,
tag,
update,
findByBackendUuid,
upsertFromCloud,
hydrateCloudEntry,
} from "./history-store.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore – cloud-sync.js is a plain JS module; types inferred at call-site
export { syncCloudHistory, hydrateCloudHistoryEntry } from "./cloud-sync.js";
export { exportThread } from "./export.js";
export type { HistoryEntry } from "./format.js";
export type { HistoryItem } from "@perplexity-user-mcp/shared";
export { loadToolConfig, getEnabledTools, saveToolConfig, watchToolConfig } from "./tool-config.js";
export type { ToolProfile } from "./tool-config.js";
export { findBrowser } from "./config.js";
export type { BrowserInfo } from "./config.js";
export { refreshAccountInfo, getModelsCacheInfo, isImpitAvailable, getImpitRuntimeDir } from "./refresh.js";
export type { RefreshResult, RefreshTier, RefreshOptions } from "./refresh.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore – doctor.js is a plain JS module; types inferred at call-site
export { runAll as runDoctor, formatReportMarkdown, CATEGORIES as DOCTOR_CATEGORIES } from "./doctor.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore – doctor-report.js is a plain JS module; types inferred at call-site
export { buildIssueBody, redactIssueBody, buildIssueUrl, decideTransport } from "./doctor-report.js";