@opencorelabs/lucidity 0.2.0 → 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.
Files changed (70) hide show
  1. package/README.md +29 -34
  2. package/bin/lucidity.js +2 -0
  3. package/dist/config.d.ts +2 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +1 -0
  6. package/dist/index.js +25 -8
  7. package/dist/mcp/clients.d.ts +21 -0
  8. package/dist/mcp/clients.d.ts.map +1 -0
  9. package/dist/mcp/clients.js +193 -0
  10. package/dist/mcp/config.d.ts +2 -1
  11. package/dist/mcp/config.d.ts.map +1 -1
  12. package/dist/mcp/paired.d.ts +2 -0
  13. package/dist/mcp/paired.d.ts.map +1 -0
  14. package/dist/mcp/paired.js +20 -0
  15. package/dist/mcp/pairedConfig.d.ts +3 -0
  16. package/dist/mcp/pairedConfig.d.ts.map +1 -0
  17. package/dist/mcp/pairedConfig.js +33 -0
  18. package/dist/setup/page.d.ts +3 -0
  19. package/dist/setup/page.d.ts.map +1 -0
  20. package/dist/setup/page.js +120 -0
  21. package/dist/setup/server.d.ts +26 -0
  22. package/dist/setup/server.d.ts.map +1 -0
  23. package/dist/setup/server.js +398 -0
  24. package/package.json +1 -1
  25. package/src/config.ts +3 -0
  26. package/src/index.ts +41 -24
  27. package/src/mcp/clients.ts +269 -0
  28. package/src/mcp/config.ts +2 -1
  29. package/src/mcp/paired.ts +22 -0
  30. package/src/mcp/pairedConfig.ts +44 -0
  31. package/src/setup/page.ts +122 -0
  32. package/src/setup/server.ts +483 -0
  33. package/vendor/mcp-server/README.md +125 -48
  34. package/vendor/mcp-server/dist/index.js +11 -5
  35. package/vendor/mcp-server/dist/tools/comments.d.ts.map +1 -1
  36. package/vendor/mcp-server/dist/tools/comments.js +16 -1
  37. package/vendor/mcp-server/dist/tools/memory.d.ts +2 -2
  38. package/vendor/mcp-server/dist/tools/memory.d.ts.map +1 -1
  39. package/vendor/mcp-server/dist/tools/memory.js +24 -14
  40. package/vendor/mcp-server/dist/tools/milestones.d.ts.map +1 -1
  41. package/vendor/mcp-server/dist/tools/milestones.js +30 -0
  42. package/vendor/mcp-server/dist/tools/notes.d.ts.map +1 -1
  43. package/vendor/mcp-server/dist/tools/notes.js +30 -5
  44. package/vendor/mcp-server/dist/tools/projects.d.ts.map +1 -1
  45. package/vendor/mcp-server/dist/tools/projects.js +15 -0
  46. package/vendor/mcp-server/dist/tools/queries.d.ts.map +1 -1
  47. package/vendor/mcp-server/dist/tools/queries.js +27 -2
  48. package/vendor/mcp-server/dist/tools/tasks.d.ts.map +1 -1
  49. package/vendor/mcp-server/dist/tools/tasks.js +37 -0
  50. package/vendor/mcp-server/package.json +1 -1
  51. package/vendor/mcp-server/src/index.ts +19 -6
  52. package/vendor/mcp-server/src/tools/comments.ts +19 -1
  53. package/vendor/mcp-server/src/tools/memory.ts +26 -12
  54. package/vendor/mcp-server/src/tools/milestones.ts +36 -0
  55. package/vendor/mcp-server/src/tools/notes.ts +35 -4
  56. package/vendor/mcp-server/src/tools/projects.ts +18 -0
  57. package/vendor/mcp-server/src/tools/queries.ts +30 -0
  58. package/vendor/mcp-server/src/tools/tasks.ts +44 -0
  59. package/vendor/shared/dist/brandArtwork.d.ts +4 -0
  60. package/vendor/shared/dist/brandArtwork.d.ts.map +1 -0
  61. package/vendor/shared/dist/brandArtwork.js +7 -0
  62. package/vendor/shared/dist/index.d.ts +1 -0
  63. package/vendor/shared/dist/index.d.ts.map +1 -1
  64. package/vendor/shared/dist/index.js +1 -0
  65. package/vendor/shared/dist/setupAppearance.d.ts +6 -0
  66. package/vendor/shared/dist/setupAppearance.d.ts.map +1 -0
  67. package/vendor/shared/dist/setupAppearance.js +17 -0
  68. package/vendor/shared/src/brandArtwork.ts +7 -0
  69. package/vendor/shared/src/index.ts +1 -0
  70. package/vendor/shared/src/setupAppearance.ts +32 -0
@@ -0,0 +1,483 @@
1
+ import {
2
+ createServer,
3
+ type IncomingMessage,
4
+ type ServerResponse,
5
+ } from 'node:http';
6
+ import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
7
+ import { hostname } from 'node:os';
8
+ import {
9
+ mkdirSync,
10
+ readFileSync,
11
+ writeFileSync,
12
+ existsSync,
13
+ unlinkSync,
14
+ linkSync,
15
+ chmodSync,
16
+ } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { spawn } from 'node:child_process';
19
+ import { z } from 'zod';
20
+ import {
21
+ ClaudeAgentExecutor,
22
+ CodexExecutor,
23
+ providerFailure,
24
+ } from '@lucidity/runtime';
25
+ import { CONFIG_DIR } from '../config.js';
26
+ import { localSetupPage } from './page.js';
27
+ import {
28
+ createClientSetup,
29
+ CLIENT_IDS,
30
+ type ClientStatus,
31
+ } from '../mcp/clients.js';
32
+
33
+ const clientChoices = z.array(z.enum(CLIENT_IDS)).max(2).default([]);
34
+
35
+ const sha = (s: string) => createHash('sha256').update(s).digest('hex');
36
+ const pendingSchema = z.object({
37
+ id: z.string().uuid(),
38
+ code: z.string().regex(/^[A-F0-9]{24}$/),
39
+ expiresAt: z.string().datetime(),
40
+ secret: z.string().regex(/^[a-f0-9]{64}$/),
41
+ key: z.string().regex(/^luc_pc_[a-f0-9]{64}$/),
42
+ apiUrl: z.string().url(),
43
+ name: z.string().min(1).max(120),
44
+ });
45
+ type Pending = z.infer<typeof pendingSchema>;
46
+ export function setupApiUrl(value: string) {
47
+ const url = new URL(value);
48
+ if (
49
+ url.username ||
50
+ url.password ||
51
+ url.search ||
52
+ url.hash ||
53
+ (url.pathname !== '/' && url.pathname !== '')
54
+ )
55
+ throw new Error('Use the API origin without a path or credentials.');
56
+ if (
57
+ url.protocol !== 'https:' &&
58
+ !(
59
+ url.protocol === 'http:' &&
60
+ ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
61
+ )
62
+ )
63
+ throw new Error(
64
+ 'Setup requires HTTPS, except for a local development API.',
65
+ );
66
+ return url.origin;
67
+ }
68
+ export function writeNewSetupConfig(
69
+ dir: string,
70
+ config: Record<string, unknown>,
71
+ ) {
72
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
73
+ const temporary = join(dir, `.setup-${randomBytes(8).toString('hex')}.json`);
74
+ writeFileSync(temporary, JSON.stringify(config, null, 2) + '\n', {
75
+ flag: 'wx',
76
+ mode: 0o600,
77
+ });
78
+ try {
79
+ linkSync(temporary, join(dir, 'config.json'));
80
+ } finally {
81
+ unlinkSync(temporary);
82
+ }
83
+ }
84
+ function acquireSetupLock(dir: string) {
85
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ const path = join(dir, 'setup.lock');
87
+ if (existsSync(path)) {
88
+ const pid = Number(readFileSync(path, 'utf8'));
89
+ if (!Number.isInteger(pid) || pid < 1)
90
+ throw new Error(
91
+ 'The saved setup lock is invalid. Your configuration has not been changed.',
92
+ );
93
+ let alive = true;
94
+ try {
95
+ process.kill(pid, 0);
96
+ } catch (e) {
97
+ if ((e as NodeJS.ErrnoException).code === 'ESRCH') alive = false;
98
+ }
99
+ if (alive)
100
+ throw new Error(
101
+ 'Setup is already open for this computer. Return to its browser window.',
102
+ );
103
+ unlinkSync(path);
104
+ }
105
+ writeFileSync(path, String(process.pid), { flag: 'wx', mode: 0o600 });
106
+ return () => {
107
+ if (existsSync(path) && readFileSync(path, 'utf8') === String(process.pid))
108
+ unlinkSync(path);
109
+ };
110
+ }
111
+ export async function checkSetupProviders() {
112
+ return Promise.all(
113
+ (['claude', 'codex'] as const).map(async (id) => {
114
+ const executor =
115
+ id === 'claude' ? new ClaudeAgentExecutor() : new CodexExecutor();
116
+ try {
117
+ await executor.models();
118
+ return {
119
+ id,
120
+ label: id === 'claude' ? 'Claude' : 'Codex',
121
+ auth: 'authenticated',
122
+ message: '',
123
+ };
124
+ } catch (e) {
125
+ const health = providerFailure(e);
126
+ return {
127
+ id,
128
+ label: id === 'claude' ? 'Claude' : 'Codex',
129
+ auth: health.auth === 'authenticated' ? 'unknown' : health.auth,
130
+ message:
131
+ health.problem === 'login'
132
+ ? id === 'claude'
133
+ ? 'Sign in with Claude Code on this computer, then check again.'
134
+ : 'Run codex login on this computer, then check again.'
135
+ : 'Could not check this provider. Confirm it is installed and your network is available, then check again.',
136
+ };
137
+ } finally {
138
+ await executor.dispose();
139
+ }
140
+ }),
141
+ );
142
+ }
143
+
144
+ export interface SetupOptions {
145
+ apiUrl?: string;
146
+ directory?: string;
147
+ fetch?: typeof globalThis.fetch;
148
+ providers?: typeof checkSetupProviders;
149
+ clients?: ReturnType<typeof createClientSetup>;
150
+ onFinish?: (start: boolean) => void;
151
+ }
152
+ export async function createSetupServer(options: SetupOptions = {}) {
153
+ const apiUrl = setupApiUrl(
154
+ options.apiUrl ?? process.env.LUCIDITY_API_URL ?? 'https://api.lucidity.my',
155
+ );
156
+ const dir = options.directory ?? CONFIG_DIR;
157
+ const pendingPath = join(dir, 'setup-pending.json');
158
+ const configPath = join(dir, 'config.json');
159
+ const clients = options.clients ?? createClientSetup({ configPath });
160
+ const token = randomBytes(32).toString('hex');
161
+ const nonce = randomBytes(18).toString('base64');
162
+ let pending: Pending | undefined;
163
+ let finished = false;
164
+ let mutation = false;
165
+ let providerCheck: ReturnType<typeof checkSetupProviders> | undefined;
166
+ if (!existsSync(configPath) && existsSync(pendingPath)) {
167
+ const parsed = pendingSchema.safeParse(
168
+ JSON.parse(readFileSync(pendingPath, 'utf8')),
169
+ );
170
+ if (!parsed.success)
171
+ throw new Error(
172
+ 'Saved setup is invalid. Your existing configuration has not been changed.',
173
+ );
174
+ if (parsed.data.apiUrl !== apiUrl)
175
+ throw new Error(
176
+ 'A connection is pending for a different Lucidity server. Finish or cancel it using that server before starting again.',
177
+ );
178
+ pending = parsed.data;
179
+ }
180
+ const api = async (path: string, body: unknown) => {
181
+ const response = await (options.fetch ?? fetch)(
182
+ apiUrl + '/api/auth/computers/' + path,
183
+ {
184
+ method: 'POST',
185
+ headers: { 'Content-Type': 'application/json' },
186
+ body: JSON.stringify(body),
187
+ signal: AbortSignal.timeout(15000),
188
+ redirect: 'error',
189
+ },
190
+ );
191
+ const value = await response.json().catch(() => ({}));
192
+ if (!response.ok)
193
+ throw new Error(
194
+ response.status === 404
195
+ ? 'This Lucidity server does not support guided setup yet. Update the server before trying again.'
196
+ : typeof value.error === 'string'
197
+ ? value.error
198
+ : 'Lucidity could not be reached. Check your connection and try again.',
199
+ );
200
+ return value;
201
+ };
202
+ const publicState = () =>
203
+ pending
204
+ ? {
205
+ name: pending.name,
206
+ code: pending.code,
207
+ approvalUrl:
208
+ (apiUrl === 'https://api.lucidity.my'
209
+ ? 'https://lucidity.my'
210
+ : apiUrl) +
211
+ '/connect-computer#code=' +
212
+ pending.code,
213
+ }
214
+ : {};
215
+ const removePending = () => {
216
+ if (existsSync(pendingPath)) unlinkSync(pendingPath);
217
+ pending = undefined;
218
+ };
219
+ async function body(req: IncomingMessage) {
220
+ const chunks: Buffer[] = [];
221
+ let size = 0;
222
+ for await (const chunk of req) {
223
+ size += chunk.length;
224
+ if (size > 2048) throw new Error('Request too large.');
225
+ chunks.push(chunk);
226
+ }
227
+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
228
+ }
229
+ const send = (res: ServerResponse, status: number, value: unknown) => {
230
+ res.writeHead(status, { 'Content-Type': 'application/json' });
231
+ res.end(JSON.stringify(value));
232
+ };
233
+ let origin = '';
234
+ const releaseLock = acquireSetupLock(dir);
235
+ const server = createServer(async (req, res) => {
236
+ res.setHeader('Cache-Control', 'no-store');
237
+ res.setHeader('Referrer-Policy', 'no-referrer');
238
+ res.setHeader('X-Content-Type-Options', 'nosniff');
239
+ res.setHeader(
240
+ 'Content-Security-Policy',
241
+ `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'`,
242
+ );
243
+ if (req.headers.host !== new URL(origin).host)
244
+ return send(res, 403, { error: 'Unrecognized setup host.' });
245
+ if (req.method === 'GET' && req.url === '/') {
246
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
247
+ res.end(localSetupPage(nonce));
248
+ return;
249
+ }
250
+ const provided = req.headers['x-setup-token'];
251
+ if (
252
+ req.method !== 'POST' ||
253
+ req.headers.origin !== origin ||
254
+ req.headers['content-type'] !== 'application/json' ||
255
+ typeof provided !== 'string' ||
256
+ !/^[a-f0-9]{64}$/.test(provided) ||
257
+ !timingSafeEqual(Buffer.from(provided), Buffer.from(token))
258
+ )
259
+ return send(res, 403, {
260
+ error: 'This setup session is unavailable. Run lucidity setup again.',
261
+ });
262
+ try {
263
+ const input = await body(req);
264
+ if (finished) return send(res, 409, { error: 'Setup has finished.' });
265
+ if (req.url === '/api/state')
266
+ return send(res, 200, {
267
+ existing: existsSync(configPath),
268
+ ...publicState(),
269
+ });
270
+ if (req.url === '/api/poll') {
271
+ if (!pending) throw new Error('Start a connection first.');
272
+ return send(
273
+ res,
274
+ 200,
275
+ await api('poll', { id: pending.id, secret: pending.secret }),
276
+ );
277
+ }
278
+ if (req.url === '/api/providers') {
279
+ providerCheck ??= (options.providers ?? checkSetupProviders)().finally(
280
+ () => {
281
+ providerCheck = undefined;
282
+ },
283
+ );
284
+ return send(res, 200, { providers: await providerCheck });
285
+ }
286
+ if (req.url === '/api/clients')
287
+ return send(res, 200, { clients: await clients.inspect() });
288
+ if (mutation)
289
+ return send(res, 409, { error: 'A setup step is already running.' });
290
+ mutation = true;
291
+ try {
292
+ if (req.url === '/api/configure-clients') {
293
+ if (!existsSync(configPath))
294
+ throw new Error('Finish connecting your account first.');
295
+ const selected = z
296
+ .object({ clients: clientChoices })
297
+ .parse(input).clients;
298
+ return send(res, 200, { clients: await clients.configure(selected) });
299
+ }
300
+ if (req.url === '/api/begin') {
301
+ if (existsSync(configPath))
302
+ throw new Error(
303
+ 'This computer is already configured. Your settings have been kept.',
304
+ );
305
+ const restart = z
306
+ .object({ restart: z.boolean().optional() })
307
+ .parse(input).restart;
308
+ if (
309
+ pending &&
310
+ !restart &&
311
+ new Date(pending.expiresAt).getTime() > Date.now()
312
+ )
313
+ return send(res, 200, publicState());
314
+ if (pending) {
315
+ await api('cancel', { id: pending.id, secret: pending.secret });
316
+ removePending();
317
+ }
318
+ const secret = randomBytes(32).toString('hex');
319
+ const key = 'luc_pc_' + randomBytes(32).toString('hex');
320
+ const name = hostname().slice(0, 120) || 'My computer';
321
+ const created = await api('begin', {
322
+ name,
323
+ secretHash: sha(secret),
324
+ keyHash: sha(key),
325
+ });
326
+ pending = pendingSchema.parse({
327
+ ...created,
328
+ secret,
329
+ key,
330
+ apiUrl,
331
+ name,
332
+ });
333
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
334
+ writeFileSync(pendingPath, JSON.stringify(pending), { mode: 0o600 });
335
+ chmodSync(pendingPath, 0o600);
336
+ return send(res, 200, publicState());
337
+ }
338
+ if (req.url === '/api/finish') {
339
+ const preferences = z
340
+ .object({
341
+ provider: z.enum(['claude', 'codex']),
342
+ tasks: z.boolean(),
343
+ scheduledWork: z.boolean(),
344
+ clients: clientChoices,
345
+ })
346
+ .parse(input);
347
+ if (!pending) throw new Error('Connect your account first.');
348
+ const approved = await api('poll', {
349
+ id: pending.id,
350
+ secret: pending.secret,
351
+ });
352
+ if (approved.status !== 'approved')
353
+ throw new Error(
354
+ 'Approve this computer in your Lucidity account first.',
355
+ );
356
+ const health = await (options.providers ?? checkSetupProviders)();
357
+ if (
358
+ !health.some(
359
+ (p) =>
360
+ p.id === preferences.provider && p.auth === 'authenticated',
361
+ )
362
+ )
363
+ throw new Error(
364
+ 'Sign in to your selected provider and check again.',
365
+ );
366
+ writeNewSetupConfig(dir, {
367
+ apiKey: pending.key,
368
+ apiUrl,
369
+ machineName: pending.name,
370
+ chatProvider: preferences.provider,
371
+ codeProvider: preferences.provider,
372
+ chatModel: 'default',
373
+ codeModel: 'default',
374
+ delivery: 'stdout',
375
+ scheduledWork: preferences.scheduledWork,
376
+ reflect: false,
377
+ weeklyReview: preferences.scheduledWork,
378
+ capabilities: {
379
+ tasks: preferences.tasks,
380
+ memory: false,
381
+ connected: false,
382
+ },
383
+ repos: [],
384
+ });
385
+ removePending();
386
+ let clientResults: ClientStatus[] = [];
387
+ if (preferences.clients.length) {
388
+ try {
389
+ clientResults = await clients.configure(preferences.clients);
390
+ } catch {
391
+ // Pairing has succeeded. A client-config failure must not send the
392
+ // user back through pairing or revoke the saved credential.
393
+ clientResults = preferences.clients.map((id) => ({
394
+ id,
395
+ label: id === 'claude' ? 'Claude Code' : 'Codex',
396
+ status: 'error',
397
+ message:
398
+ 'Your account is connected. Run lucidity setup-mcp to finish adding your tools.',
399
+ }));
400
+ }
401
+ }
402
+ finished = true;
403
+ send(res, 200, { ok: true, clients: clientResults });
404
+ setTimeout(() => {
405
+ server.close();
406
+ options.onFinish?.(true);
407
+ }, 500);
408
+ return;
409
+ }
410
+ if (req.url === '/api/cancel') {
411
+ if (pending)
412
+ await api('cancel', { id: pending.id, secret: pending.secret });
413
+ removePending();
414
+ finished = true;
415
+ send(res, 200, { ok: true });
416
+ setTimeout(() => {
417
+ server.close();
418
+ options.onFinish?.(false);
419
+ }, 500);
420
+ return;
421
+ }
422
+ send(res, 404, { error: 'Unknown setup action.' });
423
+ } finally {
424
+ mutation = false;
425
+ }
426
+ } catch (e) {
427
+ send(res, 400, {
428
+ error:
429
+ e instanceof z.ZodError
430
+ ? 'Invalid setup choice.'
431
+ : e instanceof Error
432
+ ? e.message
433
+ : 'Setup could not finish.',
434
+ });
435
+ }
436
+ });
437
+ server.once('close', releaseLock);
438
+ server.once('error', releaseLock);
439
+ server.requestTimeout = 20000;
440
+ await new Promise<void>((resolve, reject) => {
441
+ server.once('error', reject);
442
+ server.listen(0, '127.0.0.1', resolve);
443
+ });
444
+ const address = server.address();
445
+ if (!address || typeof address === 'string')
446
+ throw new Error('Could not open setup.');
447
+ origin = 'http://127.0.0.1:' + address.port;
448
+ const expires = setTimeout(
449
+ () => {
450
+ server.closeAllConnections();
451
+ server.close();
452
+ options.onFinish?.(false);
453
+ },
454
+ 30 * 60 * 1000,
455
+ );
456
+ expires.unref();
457
+ server.on('close', () => clearTimeout(expires));
458
+ return { server, url: origin + '/#session=' + token, token, origin };
459
+ }
460
+
461
+ export async function runSetup(): Promise<boolean> {
462
+ return new Promise<boolean>((resolve, reject) => {
463
+ void createSetupServer({ onFinish: resolve }).then(({ url }) => {
464
+ console.error('Open this private setup link on this computer:\n' + url);
465
+ const command =
466
+ process.platform === 'darwin'
467
+ ? 'open'
468
+ : process.platform === 'win32'
469
+ ? 'rundll32'
470
+ : 'xdg-open';
471
+ const args =
472
+ process.platform === 'win32'
473
+ ? ['url.dll,FileProtocolHandler', url]
474
+ : [url];
475
+ const child = spawn(command, args, {
476
+ stdio: 'ignore',
477
+ windowsHide: true,
478
+ });
479
+ child.on('error', () => {});
480
+ child.unref();
481
+ }, reject);
482
+ });
483
+ }
@@ -1,87 +1,164 @@
1
1
  # @lucidity/mcp-server
2
2
 
3
- MCP server for managing Lucidity tasks and projects from AI clients.
3
+ MCP server for managing Lucidity tasks, projects, milestones, comments, and local
4
+ markdown notes from Codex, Claude Code, Claude Desktop, and other MCP clients.
5
+ The same server runs over stdio for every client; each client needs its own registration.
4
6
 
5
7
  ## Installation
6
8
 
7
- ### 1. Generate API Key
8
- In the Lucidity mobile app: **Settings > API Key > Generate**
9
+ The server is included in the public `@opencorelabs/lucidity` package. Most users
10
+ should follow the [package guide](../../npm/README.md). The internal workspace
11
+ package `@lucidity/mcp-server` is not published separately.
12
+
13
+ ### Build from source or configure a custom client
14
+
15
+ ### 1. Get an API key
16
+
17
+ In the Lucidity app: **Settings > API Key > Generate**. Reuse an existing key when
18
+ adding another client: generating a new key revokes the previous one.
19
+
20
+ ### 2. Build the server and its workspace dependencies
21
+
22
+ Run from the repository root after installing dependencies with `pnpm install`:
9
23
 
10
- ### 2. Build the MCP Server
11
24
  ```bash
12
- cd packages/mcp-server
13
- pnpm build
25
+ pnpm exec turbo run build --filter=@lucidity/mcp-server...
14
26
  ```
15
27
 
16
- ### 3. Link Globally (Development)
28
+ The server depends on `@lucidity/notes` and `@lucidity/runtime`, which also need
29
+ their compiled output. This workspace package is not published separately. A global link is
30
+ optional; the commands below use an absolute entry path and the current Node
31
+ executable so they also work when a desktop client starts outside the repository.
32
+
33
+ ### 3. Register with your client
34
+
35
+ Run the following commands from the repository root, replacing the API key.
36
+
37
+ #### Codex
38
+
17
39
  ```bash
18
- # From the mcp-server directory
19
- pnpm link --global
40
+ codex mcp add lucidity \
41
+ --env LUCIDITY_API_KEY=luc_your_api_key_here \
42
+ --env LUCIDITY_API_URL=https://api.lucidity.my \
43
+ -- "$(node -p 'process.execPath')" "$PWD/packages/mcp-server/dist/index.js"
44
+ ```
45
+
46
+ Codex stores this registration in `~/.codex/config.toml` (or your configured
47
+ `CODEX_HOME`). Local desktop, CLI, and IDE clients on the same Codex host share
48
+ it. Claude's `~/.claude.json` and `.mcp.json` entries do not register this server
49
+ with Codex.
50
+
51
+ For manual configuration, add this to your personal Codex `config.toml`, using
52
+ the paths printed by `node -p 'process.execPath'` and your repository location:
53
+
54
+ ```toml
55
+ [mcp_servers.lucidity]
56
+ command = "/absolute/path/to/node"
57
+ args = ["/absolute/path/to/lucidity/packages/mcp-server/dist/index.js"]
58
+
59
+ [mcp_servers.lucidity.env]
60
+ LUCIDITY_API_KEY = "luc_your_api_key_here"
61
+ LUCIDITY_API_URL = "https://api.lucidity.my"
62
+ # Optional local notes:
63
+ # LUCIDITY_NOTES_PATH = "/absolute/path/to/notes"
20
64
  ```
21
65
 
22
- This makes the `lucidity-mcp` command available globally without publishing to npm.
66
+ Keep the API key in personal configuration, outside version control. If you
67
+ already supply it in the environment that launches Codex, you can instead set
68
+ `env_vars = ["LUCIDITY_API_KEY"]` in `[mcp_servers.lucidity]` and omit the key from
69
+ the `env` table. Desktop clients must actually inherit that environment variable.
23
70
 
24
- ### 4. Add to Claude Code
25
- Add the MCP server with `--scope user` to make it available across all projects:
71
+ Restart the client/server after adding it, then check `/mcp` in Codex CLI and ask
72
+ it to call `get_task_stats`. `codex mcp list` checks registration; a successful
73
+ tool call verifies both server startup and API authentication.
74
+
75
+ See the [official Codex MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
76
+ for project configuration, tool allowlists, and timeouts. Codex supports this
77
+ server's stdio transport and initialization instructions; no HTTP transport or
78
+ Codex-specific tool schemas are required for local use.
79
+
80
+ #### Claude Code
26
81
 
27
82
  ```bash
28
83
  claude mcp add lucidity \
29
84
  --scope user \
30
85
  -e LUCIDITY_API_KEY=luc_your_api_key_here \
31
86
  -e LUCIDITY_API_URL=https://api.lucidity.my \
32
- -- lucidity-mcp
87
+ -- "$(node -p 'process.execPath')" "$PWD/packages/mcp-server/dist/index.js"
33
88
  ```
34
89
 
35
- For local development against localhost:
36
- ```bash
37
- claude mcp add lucidity \
38
- --scope user \
39
- -e LUCIDITY_API_KEY=luc_your_api_key_here \
40
- -e LUCIDITY_API_URL=http://localhost:3001 \
41
- -- lucidity-mcp
90
+ `--scope user` makes it available across projects. Restart Claude Code after
91
+ registration. For local development, set `LUCIDITY_API_URL=http://localhost:3001`.
92
+
93
+ #### Claude Desktop
94
+
95
+ Add an entry to `~/Library/Application Support/Claude/claude_desktop_config.json`:
96
+
97
+ ```json
98
+ {
99
+ "mcpServers": {
100
+ "lucidity": {
101
+ "command": "/absolute/path/to/node",
102
+ "args": ["/absolute/path/to/lucidity/packages/mcp-server/dist/index.js"],
103
+ "env": {
104
+ "LUCIDITY_API_KEY": "luc_your_api_key_here",
105
+ "LUCIDITY_API_URL": "https://api.lucidity.my"
106
+ }
107
+ }
108
+ }
109
+ }
42
110
  ```
43
111
 
44
- **Scope options:**
45
- - `--scope user` - Available across all projects (recommended)
46
- - `--scope local` - Available only in current project (default)
47
- - `--scope project` - Shared with team via `.mcp.json` file
112
+ Merge this entry with any existing servers, then restart Claude Desktop.
48
113
 
49
- ### 5. Restart Claude Code
50
- Close and reopen Claude Code for the changes to take effect.
114
+ ## Optional local storage
51
115
 
52
- ## Verifying Installation
116
+ - `LUCIDITY_NOTES_PATH`: a markdown vault directory, enabling note operations.
117
+ Without it, note tools return an explicit configuration error; API tools still work.
118
+ - `LUCIDITY_VAULT_PATH`: Lucid's memory directory, enabling `read_memory`,
119
+ `remember`, and `forget`. These access `MEMORY.md` and share it with the daemon
120
+ if configured to the same directory. Omit this to leave memory tools unavailable.
53
121
 
54
- After installation with `--scope user`, the lucidity MCP server works from any directory:
122
+ Use absolute paths (a leading `~/` is also supported). `LUCIDITY_API_KEY` is
123
+ required at startup. `LUCIDITY_API_URL` defaults to `https://api.lucidity.my`.
55
124
 
56
- ```bash
57
- # Check if the command is available
58
- which lucidity-mcp
125
+ ## Daemon integration
59
126
 
60
- # Check user-scoped MCP configuration
61
- cat ~/.claude.json | grep -A 10 lucidity
62
- ```
127
+ `apps/daemon/src/mcp/config.ts` generates private MCP configuration for Lucid's
128
+ internal provider executors. The Claude and Codex adapters apply the corresponding
129
+ tool restrictions. This module does not install the server in external clients;
130
+ that is a separate setup operation. Registering an external client does not
131
+ change the daemon's model provider or capability settings.
63
132
 
64
133
  ## Uninstalling
65
134
 
66
- To remove the global link:
67
- ```bash
68
- cd packages/mcp-server
69
- pnpm unlink --global
70
- ```
135
+ Remove the registration from the relevant client:
71
136
 
72
- To remove from Claude Code:
73
137
  ```bash
74
- claude mcp remove lucidity
138
+ codex mcp remove lucidity
139
+ # Or, for Claude Code:
140
+ claude mcp remove lucidity --scope user
75
141
  ```
76
142
 
143
+ If you previously linked `lucidity-mcp` globally, run `pnpm unlink --global`
144
+ from `packages/mcp-server` to remove that optional link.
145
+
77
146
  ## Tools
78
147
 
79
- - **Tasks:** `list_tasks` `create_task` `update_task` `complete_task` `delete_task` `mark_task_reviewed`
148
+ - **Tasks:** `get_task` `list_tasks` `create_task` `update_task` `complete_task` `delete_task` `mark_task_reviewed`
80
149
  - **Projects:** `list_projects` `create_project` `update_project`
81
- - **Milestones:** `list_milestones` `create_milestone` `update_milestone` `delete_milestone` `get_milestone_progress`
82
- - **Comments:** `list_comments` `create_comment`
150
+ - **Milestones:** `list_milestones` `create_milestone` `update_milestone` `delete_milestone` `merge_milestones` `get_milestone_progress`
151
+ - **Comments:** `list_comments` `create_comment` `delete_comment`
83
152
  - **Queries:** `get_today` `get_week` `search` `get_task_stats` `get_unreviewed_tasks`
84
-
85
- ## Docs
86
-
87
- See [/docs/mcp-server.md](../../docs/mcp-server.md) for architecture decisions, auth design, and future opportunities.
153
+ - **Notes:** `list_notes` `read_note` `search_notes` `write_note` `edit_note`
154
+ - **Memory (opt-in):** `read_memory` `remember` `forget`
155
+
156
+ Tools advertise MCP annotations for reads, writes, destructive operations, and
157
+ access limited to the configured Lucidity account and local vaults. These are
158
+ client guidance; the API and local vault checks still enforce access.
159
+ `complete_task` toggles state, so repeating it can
160
+ undo a completion or advance a recurring task again. `create_comment.source`
161
+ uses the legacy API value `claude` for AI-authored comments from any client,
162
+ including Codex.
163
+
164
+ See [/docs/mcp-server.md](../../docs/mcp-server.md) for architecture and auth design.