-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathmcp.ts
More file actions
1867 lines (1774 loc) · 79 KB
/
Copy pathmcp.ts
File metadata and controls
1867 lines (1774 loc) · 79 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// `od mcp` - stdio MCP server that proxies project tool calls to the
// running daemon's HTTP API. Lets a coding agent in a *different* repo
// (Claude Code, Cursor, Zed) pull files from a local Open Design
// project and create project-scoped artifacts without the
// export-zip-import dance.
//
// The server itself holds no state and never touches the filesystem;
// every tool resolves to a fetch() against `OD_DAEMON_URL`. Spawn the
// MCP server with no daemon running and tool calls return a clear
// "daemon not reachable" error - the server itself still launches so
// the client can list its tool schema.
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { buildProjectRawFileUrl } from '@open-design/contracts';
import { randomUUID } from 'node:crypto';
import { postCreateArtifactRequest } from './artifacts/create.js';
const SERVER_NAME = 'open-design';
const SERVER_VERSION = '0.2.0';
const MCP_STDIO_IDLE_EXIT_MS = 30 * 60 * 1000;
type JsonObject = Record<string, unknown>;
interface RunMcpOptions { daemonUrl: string | URL }
interface CatalogItem { id: string; name?: string; title?: string; description?: string; summary?: string }
interface SkillsPayload { skills?: CatalogItem[] }
interface DesignSystemsPayload { designSystems?: CatalogItem[] }
interface ResourcePayload { skill?: { body?: string; content?: string }; designSystem?: { body?: string; content?: string }; body?: string; content?: string }
interface ProjectSummary { id: string; name: string; metadata?: JsonObject }
interface ProjectsPayload { projects?: ProjectSummary[] }
interface ProjectPayload { project?: ProjectSummary; id?: string; name?: string; metadata?: JsonObject; resolvedDir?: string }
interface ActiveContext { active?: boolean; projectId?: string; projectName?: string | null; fileName?: string | null; ageMs?: number | null }
type ResolvedProject = { id: string; name: string; source: 'uuid' | 'id' | 'exact' | 'slug' | 'substring' };
interface ProjectListCache { baseUrl: string; t: number; list: ProjectSummary[] }
interface McpArgs extends JsonObject { project?: unknown; entry?: unknown; include?: unknown; maxBytes?: unknown; path?: unknown; offset?: unknown; limit?: unknown; since?: unknown; query?: unknown; pattern?: unknown; max?: unknown; name?: unknown; content?: unknown; encoding?: unknown; artifactManifest?: unknown; confirm?: unknown; prompt?: unknown; plugin?: unknown; inputs?: unknown; agent?: unknown; model?: unknown; serviceTier?: unknown; runId?: unknown; id?: unknown; designSystem?: unknown; skill?: unknown; includeUnavailable?: unknown }
interface ProjectFileBundleEntry { name: string; mime: string; size: number | null; content: string | null; binary: boolean }
interface BundleInput { project: ProjectPayload | ProjectSummary; entry: string; files: ProjectFileBundleEntry[]; truncated: boolean; active: ActiveContext | null; resolved?: ResolvedProject | null }
interface ErrorWithCode { message?: string; code?: string; cause?: { code?: string } }
interface McpIdleExitControllerOptions {
idleMs: number;
onIdle: () => void;
}
export function _createMcpIdleExitController({
idleMs,
onIdle,
}: McpIdleExitControllerOptions) {
let timer: ReturnType<typeof setTimeout> | null = null;
let inFlight = 0;
let disposed = false;
const clear = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
const schedule = () => {
if (disposed) return;
clear();
timer = setTimeout(() => {
timer = null;
if (disposed) return;
if (inFlight > 0) {
schedule();
return;
}
disposed = true;
onIdle();
}, idleMs);
};
schedule();
return {
noteActivity() {
schedule();
},
async trackRequest<T>(fn: () => T | Promise<T>): Promise<T> {
if (disposed) {
return fn();
}
inFlight += 1;
schedule();
try {
return await fn();
} finally {
inFlight -= 1;
if (inFlight === 0) {
schedule();
}
}
},
dispose() {
disposed = true;
clear();
},
};
}
// Mimes whose body we surface as MCP `text` content. Everything else
// returns a clear error directing the caller at list_files for
// metadata, until phase 2 adds binary support.
const TEXTUAL_MIME_PATTERNS = [
/^text\//i,
/^application\/json\b/i,
/^application\/javascript\b/i,
/^application\/typescript\b/i,
/^application\/xml\b/i,
/^application\/x-(yaml|toml|httpd-php|sh)\b/i,
/\+json\b/i,
/\+xml\b/i,
/^image\/svg\+xml\b/i,
];
// Every tool here is a read against a local daemon owned by the
// current user, so they're all read-only, idempotent, and operate on
// a closed (project-scoped) namespace. Pull these into one constant
// so each tool def doesn't repeat them.
const READ_ANNOTATIONS = {
readOnlyHint: true,
idempotentHint: true,
openWorldHint: false,
};
const WRITE_ANNOTATIONS = {
readOnlyHint: false,
idempotentHint: false,
destructiveHint: false,
openWorldHint: false,
};
// Description style: short, one purpose-line per tool. Active-context
// fallback is documented once in the server `instructions` block, so
// per-tool descriptions just say "project optional" and don't repeat
// the rationale - that saves ~150 tokens per tools/list response,
// shipped to the model on every session.
const PROJECT_ARG = {
type: 'string',
description: 'Project id (UUID) or name substring. Optional; defaults to the active project (expires after ~5 minutes of no Open Design activity).',
} as const;
const TOOL_DEFS = [
{
name: 'list_projects',
description: 'List every Open Design project on this daemon.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { ...READ_ANNOTATIONS, title: 'List Open Design projects' },
},
{
name: 'get_active_context',
description:
'Project + file the user has open in Open Design right now. Returns {active:false, hint:"..."} when no project is active so the agent can ask the user to interact with Open Design (the active context expires ~5 minutes after the last user interaction). Most tools default to this when project is omitted, so you rarely need to call this directly.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { ...READ_ANNOTATIONS, title: 'What is the user looking at?' },
},
{
name: 'get_artifact',
description:
'PREFER THIS over multiple get_file calls. Bundles the entry file plus every sibling it references (HTML <script>/<link>/<img>/srcset, JSX import/require, CSS url()/@import) up to depth 3, skipping CDN/data URLs. include="all" returns every file in the project; include="shallow" returns just the entry.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
entry: {
type: 'string',
description:
"Entry file path relative to project root. Defaults to the active file or project's metadata.entryFile. Active-file fallback expires after ~5 minutes of no Open Design activity.",
},
include: {
type: 'string',
enum: ['auto', 'all', 'shallow'],
description: 'auto (default) | all | shallow',
},
maxBytes: {
type: 'number',
description:
'Soft cap on total text bytes (default 1_500_000). Also capped at 200 files. Excess files are dropped and truncated:true is set.',
},
},
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'Pull design bundle' },
},
{
name: 'get_project',
description:
'Single project metadata: name, active skill/design-system ids, entryFile, kind, timestamps, resolvedDir, and (when it has an entry file) a browser-openable previewUrl.',
inputSchema: {
type: 'object',
properties: { project: PROJECT_ARG },
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'Get Open Design project' },
},
{
name: 'get_file',
description:
'Read one project file. Text mimes only (HTML, JSX, CSS, JSON, SVG, Markdown). Binary files return an error; use list_files for metadata. Returns up to `limit` lines starting at `offset` (defaults: offset=0, limit=2000), mirroring Claude Code\'s Read tool. For files longer than the slice, the response carries an `[od:file-window ...]` marker with totalLines so you can page by re-calling with the next offset. For multi-file designs prefer get_artifact.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
path: {
type: 'string',
description:
'File path relative to project root, forward slashes. Optional; defaults to the active file when project is also omitted. Active-file fallback expires after ~5 minutes of no Open Design activity.',
},
offset: {
type: 'number',
description: '0-indexed starting line of the slice to return. Defaults to 0.',
},
limit: {
type: 'number',
description: 'Maximum number of lines to return. Defaults to 2000.',
},
},
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'Read project file' },
},
{
name: 'search_files',
description:
'Case-insensitive literal-substring search across textual files in a project. Returns up to max matches with file, 1-indexed line, and snippet.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
query: {
type: 'string',
description: 'Literal substring (not a regex), case-insensitive.',
},
pattern: {
type: 'string',
description: 'Optional glob on file name, e.g. "*.jsx".',
},
max: {
type: 'number',
description: 'Cap on matches (default 200, hard cap 1000).',
},
},
required: ['query'],
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'Search project files' },
},
{
name: 'list_files',
description:
'Project file metadata: name, path, mime, kind, size, mtime, optional artifactManifest. Pass since=<unix-ms> to cheap-poll for changes.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
since: {
type: 'number',
description: 'Unix-ms; only return files with mtime > since.',
},
},
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'List project files' },
},
{
name: 'create_artifact',
description:
'Create one normal Open Design project artifact entry file. Writes name+content, rejects existing targets, and persists artifactManifest when supplied. HTML, Markdown, and SVG entries get a default manifest when omitted. Project optional; defaults to the active project.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
name: {
type: 'string',
description: 'Output path relative to the project root, for example "codex-product/index.html" or "deck.html".',
},
content: {
type: 'string',
description: 'Entry file contents. Use encoding="base64" for base64 content.',
},
encoding: {
type: 'string',
enum: ['utf8', 'base64'],
description: 'utf8 (default) | base64',
},
artifactManifest: {
type: 'object',
additionalProperties: true,
description: 'Optional ArtifactManifest sidecar. If omitted, Open Design infers one for HTML, Markdown, or SVG entry files.',
},
},
required: ['name', 'content'],
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, title: 'Create Open Design artifact' },
},
{
name: 'write_file',
description:
'Write (or overwrite) a project file. Unlike create_artifact this does not require an ArtifactManifest and tolerates existing targets, so it is the right tool for iterating on a file the agent (or the user) already created. Project optional; defaults to the active project.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
path: {
type: 'string',
description: 'Output path relative to the project root, e.g. "deck.html" or "components/Hero.tsx".',
},
content: {
type: 'string',
description: 'File contents. Use encoding="base64" for binary payloads.',
},
encoding: {
type: 'string',
enum: ['utf8', 'base64'],
description: 'utf8 (default) | base64',
},
},
required: ['path', 'content'],
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, title: 'Write Open Design project file' },
},
{
name: 'delete_file',
description:
'Delete one file from a project. Supports nested paths (e.g. "codex-product/index.html"). Project optional; defaults to the active project.',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
path: {
type: 'string',
description: 'Project-relative path of the file to delete.',
},
},
required: ['path'],
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, destructiveHint: true, title: 'Delete Open Design project file' },
},
{
name: 'delete_project',
description:
'Permanently delete an Open Design project including its files and conversations. Requires both an explicit project id/name AND confirm:true — there is no active-project fallback because the operation is irreversible.',
inputSchema: {
type: 'object',
properties: {
project: {
type: 'string',
description: 'Project id (UUID) or name substring. Required — active-context fallback is intentionally disabled.',
},
confirm: {
type: 'boolean',
description: 'Must be literally true. Guards against an agent accidentally deleting a project while cleaning up.',
},
},
required: ['project', 'confirm'],
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, destructiveHint: true, title: 'Delete Open Design project' },
},
{
name: 'create_project',
description:
'Create a new empty Open Design project to generate into, then call start_run against it. Returns the project (with its id) plus a conversationId. The id is derived from name unless you pass one explicitly.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Human-readable project name.' },
id: {
type: 'string',
description: 'Optional project id slug ([A-Za-z0-9._-], <=128 chars). Derived from name when omitted.',
},
designSystem: {
type: 'string',
description: 'Optional design system id to attach (see the od://design-systems/... resources).',
},
skill: { type: 'string', description: 'Optional skill id to seed the project with.' },
},
required: ['name'],
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, title: 'Create Open Design project' },
},
// Discovery + generation. An external coding agent does NOT run a
// skill itself — it commissions Open Design to, via start_run. The
// daemon then spawns ITS OWN agent (Claude Code / API fallback /…)
// to do the work. So list_skills / list_plugins exist purely so the
// caller can discover what it can ask OD to generate; start_run
// kicks off the run and get_run polls it to completion. Design
// systems stay resource-only (od://design-systems/...) since they're
// reference material the caller opts into, not something to run.
{
name: 'list_skills',
description: 'List Open Design skills you can pass to start_run as a recipe. Discovery only — Open Design runs the skill, not you.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { ...READ_ANNOTATIONS, title: 'List Open Design skills' },
},
{
name: 'list_plugins',
description: 'List installed Open Design plugins (packaged design workflows) you can pass to start_run as plugin + inputs.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { ...READ_ANNOTATIONS, title: 'List Open Design plugins' },
},
{
name: 'start_run',
description:
'Commission Open Design to generate or refine a design. Open Design spawns its own agent to do the work and returns a runId immediately. Poll get_run(runId) until status is terminal, then get_artifact to pull the result. Project optional; defaults to the active project. Requires an existing project (create one first with create_project).',
inputSchema: {
type: 'object',
properties: {
project: PROJECT_ARG,
prompt: {
type: 'string',
description: 'What to make or change, in natural language. Optional when a plugin supplies its own brief.',
},
skill: {
type: 'string',
description: 'Skill id from list_skills to drive the run. Optional.',
},
plugin: {
type: 'string',
description: 'Plugin id from list_plugins to drive the run. Optional.',
},
inputs: {
type: 'object',
additionalProperties: true,
description: 'Plugin inputs object (only meaningful with plugin). Optional.',
},
agent: {
type: 'string',
description: "Which agent Open Design should run, e.g. 'claude' | 'codex' | 'opencode'. Optional; defaults to the user's configured agent.",
},
model: {
type: 'string',
description: 'Model id override for the run. Optional.',
},
serviceTier: {
type: 'string',
description: "Service tier override for the selected model, e.g. 'priority' for Codex Fast. Optional.",
},
},
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, title: 'Generate with Open Design' },
},
{
name: 'get_run',
description:
'Poll a run started by start_run. Returns status (queued|running|succeeded|failed|canceled) plus error info. On success, adds previewUrl (open it in a browser to view the rendered design) and agentMessage (the inner agent\'s textual output reassembled from the event stream — show this when there is no previewUrl, e.g. when the agent asked the user a clarifying question instead of producing files).',
inputSchema: {
type: 'object',
properties: {
runId: { type: 'string', description: 'Run id returned by start_run.' },
},
required: ['runId'],
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'Check Open Design run' },
},
{
name: 'cancel_run',
description: 'Request cancellation of an in-flight run started by start_run.',
inputSchema: {
type: 'object',
properties: {
runId: { type: 'string', description: 'Run id returned by start_run.' },
},
required: ['runId'],
additionalProperties: false,
},
annotations: { ...WRITE_ANNOTATIONS, title: 'Cancel Open Design run' },
},
{
name: 'list_agents',
description:
'List the agent CLIs Open Design can run for start_run.agent. Returns only installed (available) agents by default — pass includeUnavailable:true to also see agents we know about but that are not on PATH (each carries an installUrl for the user). Each entry includes id, name, version, and up to 10 sample models (modelsCount carries the real total).',
inputSchema: {
type: 'object',
properties: {
includeUnavailable: {
type: 'boolean',
description: 'When true, include agents whose binary is not installed. Defaults to false.',
},
},
additionalProperties: false,
},
annotations: { ...READ_ANNOTATIONS, title: 'List Open Design agents' },
},
];
export async function runMcpStdio({ daemonUrl }: RunMcpOptions): Promise<void> {
const baseUrl = String(daemonUrl).replace(/\/$/, '');
let closeTransportForIdle: (() => void) | null = null;
const idleExit = _createMcpIdleExitController({
idleMs: MCP_STDIO_IDLE_EXIT_MS,
onIdle: () => closeTransportForIdle?.(),
});
const withMcpActivity =
<Args extends unknown[], Result>(handler: (...args: Args) => Result | Promise<Result>) =>
(...args: Args) =>
idleExit.trackRequest(() => handler(...args));
const server = new Server(
{ name: SERVER_NAME, version: SERVER_VERSION },
{
capabilities: { tools: {}, resources: {} },
instructions: [
'Open Design (OD) is a local-first design workspace. The user typically',
'has OD running on their machine; each project contains a rendered',
'artifact (HTML/JSX/CSS) plus its source files.',
'',
'Active context: get_artifact, get_project, get_file, search_files,',
'and list_files all accept project as OPTIONAL. When omitted, they',
'default to the project the user has open in OD right now; get_file',
'and get_artifact additionally default to the active file. So when',
'the user says "this file" / "the design I have open" / "find X",',
'just call the tool without project - no need to ask first. The',
'response carries usedActiveContext so you can confirm which',
'project/file you hit. Pass project explicitly to override.',
'',
'Pulling design context:',
' - get_artifact() - entry file PLUS every referenced sibling',
' (tokens CSS, JSX modules, imported assets) in one call.',
' PREFER THIS over multiple get_file calls when the user',
' wants to understand or extend a design.',
' - get_file(path) for a single known file. Returns up to 2000',
' lines starting at offset (default 0) and stamps a',
' [od:file-window ...] marker when the file is longer; page',
' by re-calling with the next offset.',
' - search_files(query) to find a class/component/copy string',
' without fetching every file.',
' - list_files for metadata only.',
' - create_artifact(name, content) to create one normal artifact',
' entry file in the active or specified project. It rejects',
' existing targets and can accept an artifactManifest sidecar.',
' - write_file(path, content) to overwrite or freshly create any',
' project file when an ArtifactManifest is not required.',
' Use this to iterate on a file create_artifact already wrote.',
' - delete_file(path) to remove one project file (nested paths ok).',
' - delete_project(project, confirm:true) for irreversible project',
' removal — requires explicit project + confirm:true.',
' - list_projects to discover what is available on this daemon.',
' - get_active_context() if you want the active project/file',
' explicitly without making any other tool call.',
'',
'To make Open Design GENERATE or refine a design (rather than just',
'read/edit files), commission a run - you do not run skills yourself:',
' - list_skills / list_plugins to see what you can ask OD to make.',
' - list_agents when you need to pass start_run.agent — do not',
' guess "claude" / "codex" / "opencode"; only agents in the',
' returned list will actually spawn on this machine.',
' - create_project(name) first if you need a fresh project to',
' generate into; start_run requires an existing project.',
' - start_run(prompt, [skill], [plugin], [inputs]) kicks off generation in',
' the active or named project and returns a runId immediately.',
' Open Design spawns its own agent to do the work.',
' - get_run(runId) polls until status is succeeded/failed/canceled;',
' on success it returns a previewUrl you can open in a browser',
' and a hint to pull the files with get_artifact.',
' - cancel_run(runId) aborts an in-flight run.',
'',
'Generation patience: Open Design runs typically take 5–30',
'minutes. Polls returning status:running with unchanged file',
'mtimes is the inner agent thinking, not a hang. Do NOT cancel',
'and substitute write_file as a "faster" workaround — that',
'throws away the pipeline\'s design quality and is exactly the',
'failure mode this surface is meant to avoid. Poll every 30–60',
'seconds, tell the user "still working" between polls, and let',
'the run finish. Only call cancel_run if the user explicitly',
'asks you to abort.',
'',
'Ambiguous-format requests: words like "PPT" / "deck" / "slides" /',
'"presentation" / "document" / "PDF" / "doc" map to two different',
'deliverables — Open Design natively produces browser-viewable',
'HTML/SVG (including HTML-rendered decks), but the user may want a',
'real binary file (.pptx / .docx / .pdf) which Open Design does NOT',
'produce and which you would have to export yourself from OD\'s',
'output. When the user\'s request is ambiguous, ASK them which one',
'they want before kicking off work; do not silently pick one and do',
'not run both paths in parallel.',
'',
'Project arguments accept either a UUID or a name substring',
'(e.g. "recaptr"); the server resolves the latter. When a project',
'is matched by slug or substring the response carries',
'resolvedProject:{id,name} so you can confirm which project was',
'resolved. Verify with the user if the match was unexpected.',
'',
'Reference material is exposed as MCP resources, not tools - read',
'od://design-systems/<id>/DESIGN.md when you need the brand spec',
'for a design (palette, typography, voice). Skills are similarly',
'available at od://skills/<id>/SKILL.md but are mostly relevant',
'when the user asks about how a particular artifact was generated.',
'',
'When extending an Open Design design in another codebase, pull',
'the full bundle once with get_artifact and work from those files',
'locally - do not fetch files one-by-one if you can avoid it.',
].join('\n'),
},
);
server.setRequestHandler(ListToolsRequestSchema, withMcpActivity(async () => ({
tools: TOOL_DEFS,
})));
server.setRequestHandler(ListResourcesRequestSchema, withMcpActivity(async () => {
const [skillsData, dsData] = await Promise.all([
getJson<SkillsPayload>(`${baseUrl}/api/skills`).catch((): SkillsPayload => ({ skills: [] })),
getJson<DesignSystemsPayload>(`${baseUrl}/api/design-systems`).catch((): DesignSystemsPayload => ({ designSystems: [] })),
]);
const resources = [
{
uri: 'od://focus/active',
name: 'Active Open Design context',
description: 'The project/file the user has open in Open Design right now.',
mimeType: 'application/json',
},
];
for (const s of skillsData?.skills || []) {
resources.push({
uri: `od://skills/${encodeURIComponent(s.id)}/SKILL.md`,
name: `Skill: ${s.name || s.id}`,
description: oneLine(s.description) ?? '',
mimeType: 'text/markdown',
});
}
for (const d of dsData?.designSystems || []) {
resources.push({
uri: `od://design-systems/${encodeURIComponent(d.id)}/DESIGN.md`,
name: `Design system: ${d.title || d.name || d.id}`,
description: oneLine(d.summary) ?? '',
mimeType: 'text/markdown',
});
}
return { resources };
}));
server.setRequestHandler(ReadResourceRequestSchema, withMcpActivity(async (req) => {
const uri = req.params?.uri;
if (uri === 'od://focus/active') {
const data = await getJson<ActiveContext>(`${baseUrl}/api/active`);
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify(data, null, 2),
},
],
};
}
const m = String(uri || '').match(/^od:\/\/(skills|design-systems)\/([^/]+)\/(.+)$/);
if (!m) {
throw new Error(`unsupported resource URI: ${uri}`);
}
const [, kind, id] = m as [string, 'skills' | 'design-systems', string, string];
const route = kind === 'skills' ? 'skills' : 'design-systems';
const data = await getJson<ResourcePayload>(
`${baseUrl}/api/${route}/${encodeURIComponent(decodeURIComponent(id))}`,
);
const text =
data?.skill?.body ??
data?.skill?.content ??
data?.designSystem?.body ??
data?.designSystem?.content ??
data?.body ??
data?.content ??
'';
return {
contents: [
{
uri,
mimeType: 'text/markdown',
text,
},
],
};
}));
server.setRequestHandler(CallToolRequestSchema, withMcpActivity(async (req) => {
const name = req.params?.name;
const args: McpArgs = (req.params?.arguments ?? {}) as McpArgs;
return handleMcpToolCall(baseUrl, name, args);
}));
const transport = new StdioServerTransport();
try {
closeTransportForIdle = () => {
void transport.close().catch(() => {});
};
await server.connect(transport);
const sdkOnMessage = transport.onmessage;
transport.onmessage = (...args) => {
idleExit.noteActivity();
sdkOnMessage?.(...args);
};
// server.connect() only *starts* the transport; it resolves once the
// stdio reader is wired up, not when the stream closes. Hold the
// process open until the client disconnects (stdin EOF) so the cli.ts
// top-level `process.exit(0)` doesn't kill us mid-handshake.
await new Promise<void>((resolve) => {
const sdkOnClose = transport.onclose;
let finished = false;
const done = () => {
if (finished) return;
finished = true;
idleExit.dispose();
resolve();
};
transport.onclose = () => {
sdkOnClose?.();
done();
};
const closeTransportForStdin = () => {
void transport.close().catch(() => done());
};
process.stdin.once('end', closeTransportForStdin);
process.stdin.once('close', closeTransportForStdin);
});
} finally {
idleExit.dispose();
closeTransportForIdle = null;
}
}
function ok(payload: unknown) {
const text =
typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);
return { content: [{ type: 'text', text }] };
}
function errorResult(message: string) {
return { isError: true, content: [{ type: 'text', text: message }] };
}
function requireString(v: unknown, name: string): asserts v is string {
if (typeof v !== 'string' || v.length === 0) {
throw new Error(`${name} is required (string).`);
}
}
async function handleMcpToolCall(baseUrl: string, name: unknown, args: McpArgs) {
try {
switch (name) {
case 'list_projects':
return ok(await getJson<ProjectsPayload>(`${baseUrl}/api/projects`));
case 'get_active_context': {
const data = await getJson<ActiveContext>(`${baseUrl}/api/active`);
if (!data || data.active === false) {
return ok({
active: false,
hint: 'Open Design has no active project right now. The active context expires about 5 minutes after the last user interaction with Open Design, so the user may need to click into a project (or switch tabs inside one) to wake it up. Alternatively, pass project="<id-or-name>" to other tools to bypass active context entirely.',
});
}
return ok(data);
}
case 'get_project': {
const { id, resolved, active } = await resolveProjectArg(baseUrl, args.project);
const data = await getJson<ProjectPayload>(`${baseUrl}/api/projects/${encodeURIComponent(id)}`);
const project = data?.project ?? data;
const resolvedDir = typeof data?.resolvedDir === 'string' ? data.resolvedDir : null;
const declaredEntry = project?.metadata?.entryFile ?? null;
const entryFile = await resolveProjectEntry(baseUrl, id, declaredEntry);
const previewUrl = rawPreviewUrl(baseUrl, id, entryFile);
// Build the studio deep link too — needs the project's
// default conversation, which we look up once. Cheap to skip
// when the daemon has no webBaseUrl configured.
const webBase = await getWebBaseUrl(baseUrl);
const conversationId = webBase ? await getDefaultConversationId(baseUrl, id) : null;
const studioUrl = buildStudioUrl(webBase, id, conversationId, entryFile);
return ok(
withActiveEcho(
{
...project,
entryFile,
kind: project?.metadata?.kind ?? null,
resolvedDir,
// previewUrl: open in a browser to view the rendered
// design directly (HTML entries render; see
// rawPreviewUrl). studioUrl: open the OD studio page
// that shows the rendered file alongside the chat
// history for the project. Both omitted when their
// prerequisites aren't met.
...(previewUrl ? { previewUrl } : {}),
...(studioUrl ? { studioUrl } : {}),
},
active,
resolved,
),
);
}
case 'list_files': {
const { id, resolved, active } = await resolveProjectArg(baseUrl, args.project);
const params = new URLSearchParams();
if (typeof args.since === 'number' && Number.isFinite(args.since)) params.set('since', String(args.since));
const qs = params.toString();
const url = `${baseUrl}/api/projects/${encodeURIComponent(id)}/files${qs ? `?${qs}` : ''}`;
return ok(withActiveEcho(await getJson(url), active, resolved));
}
case 'get_file': {
const { id, resolved, active } = await resolveProjectArg(baseUrl, args.project);
let path = typeof args.path === 'string' ? args.path : '';
if (!path && active && active.fileName) {
path = active.fileName;
}
requireString(path, 'path');
const offset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.max(0, Math.floor(args.offset)) : 0;
const limit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.max(1, Math.floor(args.limit)) : 2000;
return await getFile(baseUrl, id, path, active, resolved, offset, limit);
}
case 'get_artifact':
return await getArtifact(
baseUrl,
args.project,
args.entry,
args.include,
args.maxBytes,
);
case 'search_files': {
const { id, resolved, active } = await resolveProjectArg(baseUrl, args.project);
requireString(args.query, 'query');
const params = new URLSearchParams({ q: String(args.query) });
if (args.pattern) params.set('pattern', String(args.pattern));
if (args.max) params.set('max', String(args.max));
return ok(
withActiveEcho(
await getJson(
`${baseUrl}/api/projects/${encodeURIComponent(id)}/search?${params.toString()}`,
),
active,
resolved,
),
);
}
case 'create_artifact':
return await createArtifact(baseUrl, args);
case 'write_file':
return await writeFile(baseUrl, args);
case 'delete_file':
return await deleteFile(baseUrl, args);
case 'delete_project':
return await deleteProject(baseUrl, args);
case 'create_project':
return await createProject(baseUrl, args);
case 'list_skills':
return ok(await getJson<SkillsPayload>(`${baseUrl}/api/skills`));
case 'list_plugins':
return ok(await listPlugins(baseUrl));
case 'list_agents':
return ok(await listAgents(baseUrl, args.includeUnavailable === true));
case 'start_run':
return await startRun(baseUrl, args);
case 'get_run':
return await getRun(baseUrl, args);
case 'cancel_run': {
requireString(args.runId, 'runId');
return ok(
await postJson<JsonObject>(
`${baseUrl}/api/runs/${encodeURIComponent(args.runId)}/cancel`,
{},
),
);
}
default:
return errorResult(`unknown tool: ${name}`);
}
} catch (err) {
return errorResult(formatError(err, baseUrl));
}
}
async function writeFile(baseUrl: string, args: McpArgs) {
const { id, resolved, active } = await resolveProjectArg(baseUrl, args.project);
// The daemon route requires its argv field to be called `name`; the
// MCP-facing surface uses `path` to match the rest of the file tools.
requireString(args.path, 'path');
requireString(args.content, 'content');
const encoding = args.encoding === 'base64' ? 'base64' : 'utf8';
// No `artifact: true` and no `overwrite: false`: the route then takes
// the default writeProjectFile path, which overwrites the target. This
// is the exact shape `od files write` uses (see apps/daemon/src/cli.ts).
const url = `${baseUrl}/api/projects/${encodeURIComponent(id)}/files`;
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: args.path, content: args.content, encoding }),
});
if (!resp.ok) {
return errorResult(await formatDaemonError(resp, url));
}
const json = (await resp.json()) as JsonObject;
return ok(withActiveEcho(json, active, resolved));
}
async function deleteFile(baseUrl: string, args: McpArgs) {
const { id, resolved, active } = await resolveProjectArg(baseUrl, args.project);
requireString(args.path, 'path');
// /api/projects/:id/raw/* accepts nested paths; /api/projects/:id/files/:name
// does not. Mirror the create_artifact surface, which already lets agents
// address files like "codex-product/index.html".
const segments = args.path
.split('/')
.filter((s) => s.length > 0)
.map(encodeURIComponent);
const url = `${baseUrl}/api/projects/${encodeURIComponent(id)}/raw/${segments.join('/')}`;
const resp = await fetch(url, { method: 'DELETE' });
if (!resp.ok) {
return errorResult(await formatDaemonError(resp, url));
}
const json = (await resp.json()) as JsonObject;
return ok(withActiveEcho(json, active, resolved));
}
async function deleteProject(baseUrl: string, args: McpArgs) {
// Active-context fallback is intentionally disabled: the daemon's
// DELETE /api/projects/:id is irreversible (purges the row and the
// on-disk project directory), so we never want it to fire against the
// wrong project just because the user happened to have one open. The
// confirm flag is a second belt for agents that auto-clean.
if (typeof args.project !== 'string' || args.project.length === 0) {
return errorResult('project is required (no active-context fallback for delete_project).');
}
if (args.confirm !== true) {
return errorResult('confirm:true is required to delete a project (this cannot be undone).');
}
const { id, resolved } = await resolveProjectArg(baseUrl, args.project);
const url = `${baseUrl}/api/projects/${encodeURIComponent(id)}`;
const resp = await fetch(url, { method: 'DELETE' });
if (!resp.ok) {
return errorResult(await formatDaemonError(resp, url));
}
const json = (await resp.json()) as JsonObject;
// The tool accepts a name substring (see resolveProjectId), so the
// caller needs the resolvedProject echo to confirm which project was
// actually destroyed — same contract write_file/delete_file follow
// via withActiveEcho. active is always null here because the
// active-context fallback is intentionally disabled above.
return ok(withActiveEcho(json, null, resolved));
}
async function formatDaemonError(resp: Response, url: string): Promise<string> {
const body = await safeText(resp);
let detail = body || resp.statusText;
try {
const parsed = JSON.parse(body) as { error?: { message?: string; code?: string } };
if (parsed?.error?.message) {
detail = `${parsed.error.code ?? 'error'}: ${parsed.error.message}`;
}
} catch {
// body wasn't JSON; fall through with the raw text.
}
return `daemon ${resp.status} on ${url}: ${detail}`;
}
async function postJson<T>(url: string, body: unknown): Promise<T> {
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body ?? {}),
});
if (!resp.ok) {
throw new Error(await formatDaemonError(resp, url));
}
return (await resp.json()) as T;
}
// Create an empty project to generate into. start_run needs an existing
// project; without this an external agent could only work on projects
// the user had already created in Open Design.
//
// skipDiscoveryBrief defaults to true: the outer agent (Codex, Cursor,
// …) IS the user-facing surface, so OD's own interactive discovery
// stage would create a confusing nested-clarification loop where OD's
// <question-form> output ends up dropped from the MCP response because
// no project file is produced. Better to let the outer agent gather
// requirements directly and pass a precise prompt to start_run.
async function createProject(baseUrl: string, args: McpArgs) {
requireString(args.name, 'name');
const id =
typeof args.id === 'string' && args.id.length > 0
? args.id
: slugifyProjectId(args.name);
const body: JsonObject = { id, name: args.name, skipDiscoveryBrief: true };
if (typeof args.designSystem === 'string' && args.designSystem.length > 0) {
body.designSystemId = args.designSystem;
}
if (typeof args.skill === 'string' && args.skill.length > 0) {
body.skillId = args.skill;