@tenonai/yew 0.0.0-stage → 1.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 (133) hide show
  1. package/CHANGELOG.md +273 -0
  2. package/LICENSE +21 -0
  3. package/README.md +64 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +211 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +58 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +127 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +268 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +120 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +144 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +343 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +465 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +70 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +180 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +43 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +77 -0
  82. package/dist/server/skills.js +263 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-BtK_SzpF.css +1 -0
  115. package/web/dist/assets/index-C0rnUFI-.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,180 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { fromJigEnv } from "./from-jig.js";
7
+ /**
8
+ * The MCP servers Yew sets up by itself (blueprint 6.10, item 38): a browser and control of this
9
+ * computer. Yew does not build these in; it runs two open-source servers.
10
+ *
11
+ * - browser: Playwright MCP by Microsoft (Apache-2.0). It opens its own Chrome window with a
12
+ * profile kept in Yew's data folder, so sign-ins made there stay, apart from the person's Chrome.
13
+ * - computer: computer-use-mcp by Adam Jones (MIT). Screenshots, mouse and keyboard for the whole
14
+ * screen; macOS asks once for Screen Recording and Accessibility for the program that runs Yew.
15
+ *
16
+ * What runs is fixed by `mcp-builtin/package-lock.json`, which ships with Yew: every package of
17
+ * both dependency trees at one version with its hash. The first time a server is needed Yew installs
18
+ * exactly that into its data folder (`npm ci`, without install scripts) and from then on starts the
19
+ * servers with node from there. Nothing is resolved at run time, so what runs changes only when Yew
20
+ * is updated.
21
+ *
22
+ * An entry of the same name in mcp.json replaces one of these; `{"disabled": true}` turns it off.
23
+ * `YEW_MCP_BUILTIN=off` leaves them out, for a throwaway Yew that should start nothing.
24
+ */
25
+ const SOURCE = fileURLToPath(new URL("../../mcp-builtin/", import.meta.url));
26
+ const FILES = ["package.json", "package-lock.json"];
27
+ /** Where the servers are installed. */
28
+ const installDir = (yewHome) => join(yewHome, "mcp-builtin");
29
+ /**
30
+ * The common servers Yew adds that run on this computer (Gitee, Notion, Sentry; blueprint 6.11, item
31
+ * 40) are installed the same way, each from its own lock file in `mcp-builtin/presets/<id>`, into
32
+ * `<data folder>/mcp-presets/<id>`, the first time it is used. This is where each one's program is in
33
+ * its package.
34
+ */
35
+ const PRESET_PROGRAMS = {
36
+ gitee: "@gitee/mcp-gitee/bin/index.js",
37
+ notion: "@notionhq/notion-mcp-server/bin/cli.mjs",
38
+ sentry: "@sentry/mcp-server/dist/sentry-mcp.cjs",
39
+ };
40
+ export const INSTALLED_PRESETS = Object.keys(PRESET_PROGRAMS);
41
+ /**
42
+ * How the preset `id` is started: with node from Yew's data folder, with a small part of Yew's
43
+ * environment and the entry's own variables (its token). Null for a preset Yew does not install.
44
+ */
45
+ export function presetMcp(yewHome, id) {
46
+ const program = Object.hasOwn(PRESET_PROGRAMS, id) ? PRESET_PROGRAMS[id] : undefined;
47
+ if (!program)
48
+ return null;
49
+ return {
50
+ command: process.execPath,
51
+ args: [join(yewHome, "mcp-presets", id, "node_modules", ...program.split("/"))],
52
+ ownEnv: true,
53
+ preset: id,
54
+ };
55
+ }
56
+ export function builtinMcp(yewHome, env = process.env) {
57
+ if (fromJigEnv(env, "MCP_BUILTIN") === "off")
58
+ return {};
59
+ const modules = join(installDir(yewHome), "node_modules");
60
+ return {
61
+ browser: {
62
+ command: process.execPath,
63
+ args: [
64
+ join(modules, "@playwright", "mcp", "cli.js"),
65
+ "--user-data-dir",
66
+ join(yewHome, "browser"),
67
+ // Page snapshots and screenshots it saves; otherwise they land in the folder Yew was started in.
68
+ "--output-dir",
69
+ join(yewHome, "tmp", "browser"),
70
+ ],
71
+ ownEnv: true,
72
+ },
73
+ computer: {
74
+ command: process.execPath,
75
+ args: [join(modules, "computer-use-mcp", "dist", "main.js")],
76
+ ownEnv: true,
77
+ },
78
+ };
79
+ }
80
+ /** Runs `npm ci` in a folder; rejects with the end of npm's output when it fails. */
81
+ function npmCi(folder, env) {
82
+ return new Promise((resolve, reject) => {
83
+ const child = spawn("npm", ["ci", "--ignore-scripts", "--no-audit", "--no-fund"], {
84
+ cwd: folder,
85
+ env,
86
+ stdio: ["ignore", "pipe", "pipe"],
87
+ });
88
+ let output = "";
89
+ const keep = (chunk) => {
90
+ output = (output + chunk.toString("utf8")).slice(-2000);
91
+ };
92
+ child.stdout.on("data", keep);
93
+ child.stderr.on("data", keep);
94
+ child.on("error", (error) => reject(new Error(`npm could not be started: ${error.message}`)));
95
+ child.on("close", (code) => code === 0 ? resolve() : reject(new Error(`npm ci failed (${code}): ${output.trim()}`)));
96
+ });
97
+ }
98
+ /**
99
+ * Makes sure what a lock file names is installed in a folder. Done once per lock file: a marker holds
100
+ * its hash, so an update of Yew that changes the lock installs again and anything else returns at
101
+ * once. A failed install leaves no marker and is tried again next time.
102
+ */
103
+ function lockedInstaller(options, source, folder, what) {
104
+ const marker = join(folder, ".installed");
105
+ const install = options.install ?? npmCi;
106
+ let running = null;
107
+ const run = async () => {
108
+ const wanted = createHash("sha256")
109
+ .update(readFileSync(join(source, "package-lock.json")))
110
+ .digest("hex");
111
+ if (existsSync(marker) && readFileSync(marker, "utf8").trim() === wanted)
112
+ return;
113
+ options.log?.(`mcp: installing ${what} from npm`);
114
+ mkdirSync(folder, { recursive: true });
115
+ for (const file of FILES)
116
+ copyFileSync(join(source, file), join(folder, file));
117
+ await install(folder, serverEnv(options.env ?? process.env));
118
+ writeFileSync(marker, `${wanted}\n`);
119
+ };
120
+ return () => {
121
+ running ??= run().finally(() => {
122
+ running = null;
123
+ });
124
+ return running;
125
+ };
126
+ }
127
+ /** Makes sure Yew's own two servers are installed as the lock file that ships with this Yew says. */
128
+ export function builtinInstaller(options) {
129
+ return lockedInstaller(options, options.source ?? SOURCE, installDir(options.yewHome), "Yew's own servers (browser, computer control)");
130
+ }
131
+ /**
132
+ * What the hub calls before it starts a server Yew runs from its data folder: installs Yew's own
133
+ * servers, or the preset the server is.
134
+ */
135
+ export function mcpInstaller(options) {
136
+ const builtin = builtinInstaller(options);
137
+ const presets = new Map();
138
+ return (config) => {
139
+ const id = config.preset;
140
+ if (!id)
141
+ return builtin();
142
+ let install = presets.get(id);
143
+ if (!install) {
144
+ install = lockedInstaller(options, join(options.source ?? SOURCE, "presets", id), join(options.yewHome, "mcp-presets", id), `the ${id} server`);
145
+ presets.set(id, install);
146
+ }
147
+ return install();
148
+ };
149
+ }
150
+ /**
151
+ * What a server Yew sets up by itself is given of Yew's environment: where programs and the home
152
+ * folder are, the language, and proxy settings. Not the rest, which in a person's shell often
153
+ * holds keys for other services.
154
+ */
155
+ const PASSED = new Set([
156
+ "PATH",
157
+ "HOME",
158
+ "USER",
159
+ "LOGNAME",
160
+ "SHELL",
161
+ "TMPDIR",
162
+ "LANG",
163
+ "LC_ALL",
164
+ "LC_CTYPE",
165
+ "TZ",
166
+ "DISPLAY",
167
+ "WAYLAND_DISPLAY",
168
+ "XAUTHORITY",
169
+ "HTTP_PROXY",
170
+ "HTTPS_PROXY",
171
+ "ALL_PROXY",
172
+ "NO_PROXY",
173
+ "http_proxy",
174
+ "https_proxy",
175
+ "all_proxy",
176
+ "no_proxy",
177
+ ]);
178
+ export function serverEnv(env) {
179
+ return Object.fromEntries(Object.entries(env).filter(([name]) => PASSED.has(name)));
180
+ }
@@ -0,0 +1,305 @@
1
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { presetPackage } from "../shared/mcp-presets.js";
4
+ import { conflict, invalid, notFound } from "./errors.js";
5
+ /**
6
+ * Changes to `mcp.json` made from the settings (blueprint 6.10, item 29). The file keeps the shape
7
+ * people write by hand and `yew mcp list` reads: entries Yew does not understand, other top-level
8
+ * keys and `${NAME}` references stay as they are. Values of environment variables and headers may
9
+ * be secrets, so what is shown of a server carries their names only.
10
+ */
11
+ export const MCP_NAME = /^[A-Za-z0-9_-]{1,32}$/;
12
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,99}$/;
13
+ /** An HTTP header name (RFC 9110 token). */
14
+ const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,100}$/;
15
+ const MAX_SERVERS = 50;
16
+ const MAX_ARGS = 100;
17
+ const MAX_VALUES = 50;
18
+ const MAX_VALUE = 8192;
19
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
20
+ const mcpFile = (yewHome) => join(yewHome, "mcp.json");
21
+ /** The file as it is written, with the object that holds the servers (`mcpServers`, or `servers`). */
22
+ function readFile(yewHome) {
23
+ const file = mcpFile(yewHome);
24
+ if (!existsSync(file)) {
25
+ const servers = {};
26
+ return { doc: { mcpServers: servers }, servers };
27
+ }
28
+ let doc;
29
+ try {
30
+ doc = JSON.parse(readFileSync(file, "utf8"));
31
+ }
32
+ catch {
33
+ doc = null;
34
+ }
35
+ if (!isObject(doc)) {
36
+ // Not overwritten: the person may have servers in it that a typo is hiding.
37
+ throw conflict("mcp.json in Yew's data folder is not valid JSON. Correct it by hand first.", undefined, "mcp-unreadable");
38
+ }
39
+ const key = doc.mcpServers === undefined && doc.servers !== undefined ? "servers" : "mcpServers";
40
+ if (doc[key] !== undefined && !isObject(doc[key])) {
41
+ throw conflict(`"${key}" in mcp.json is not an object. Correct it by hand first.`, undefined, "mcp-unreadable");
42
+ }
43
+ const servers = (doc[key] ?? {});
44
+ doc[key] = servers;
45
+ return { doc, servers };
46
+ }
47
+ /** Written beside the file and moved into place, so a reader never sees half of it. */
48
+ function writeFile(yewHome, doc) {
49
+ const file = mcpFile(yewHome);
50
+ const draft = `${file}.${process.pid}.tmp`;
51
+ // Readable by the person only: values in it may be secrets.
52
+ writeFileSync(draft, `${JSON.stringify(doc, null, 2)}\n`, { mode: 0o600 });
53
+ renameSync(draft, file);
54
+ }
55
+ const names = (value) => (isObject(value) ? Object.keys(value) : []);
56
+ function view(name, entry) {
57
+ const disabled = entry.disabled === true;
58
+ if (typeof entry.url === "string" && /^https?:\/\//.test(entry.url)) {
59
+ return {
60
+ name,
61
+ kind: "http",
62
+ builtin: false,
63
+ disabled,
64
+ command: null,
65
+ args: [],
66
+ envNames: [],
67
+ url: entry.url,
68
+ headerNames: names(entry.headers),
69
+ oauthClient: isObject(entry.oauth) && typeof entry.oauth.clientId === "string",
70
+ };
71
+ }
72
+ const pkg = typeof entry.preset === "string" ? presetPackage(entry.preset) : null;
73
+ if (pkg) {
74
+ return {
75
+ name,
76
+ kind: "stdio",
77
+ builtin: false,
78
+ disabled,
79
+ command: null,
80
+ args: [],
81
+ envNames: names(entry.env),
82
+ url: null,
83
+ headerNames: [],
84
+ oauthClient: false,
85
+ package: pkg,
86
+ };
87
+ }
88
+ if (typeof entry.command === "string" && entry.command) {
89
+ return {
90
+ name,
91
+ kind: "stdio",
92
+ builtin: false,
93
+ disabled,
94
+ command: entry.command,
95
+ args: Array.isArray(entry.args) ? entry.args.filter((arg) => typeof arg === "string") : [],
96
+ envNames: names(entry.env),
97
+ url: null,
98
+ headerNames: [],
99
+ oauthClient: false,
100
+ };
101
+ }
102
+ return null;
103
+ }
104
+ /** A built-in server as the settings show it; `off` when mcp.json turns it off. */
105
+ function builtinView(name, builtin, off) {
106
+ return {
107
+ name,
108
+ kind: "stdio",
109
+ builtin: true,
110
+ disabled: off,
111
+ command: builtin[name]?.command ?? null,
112
+ args: builtin[name]?.args ?? [],
113
+ envNames: [],
114
+ url: null,
115
+ headerNames: [],
116
+ oauthClient: false,
117
+ };
118
+ }
119
+ /** In mcp.json a built-in server is either replaced by a full entry or turned off by `disabled`. */
120
+ const turnsOff = (entry) => isObject(entry) && entry.disabled === true && !view("x", entry);
121
+ /** The servers Yew runs: its own first, then the file's in the file's order. */
122
+ export function listMcpEntries(yewHome, builtin = {}) {
123
+ const { servers } = readFile(yewHome);
124
+ const own = Object.keys(builtin)
125
+ .filter((name) => !Object.hasOwn(servers, name) || turnsOff(servers[name]))
126
+ .map((name) => builtinView(name, builtin, turnsOff(servers[name])));
127
+ const written = Object.entries(servers).flatMap(([name, entry]) => {
128
+ const shown = MCP_NAME.test(name) && isObject(entry) ? view(name, entry) : null;
129
+ return shown ? [shown] : [];
130
+ });
131
+ return [...own, ...written];
132
+ }
133
+ function checkValues(values, pattern, field) {
134
+ const entries = Object.entries(values);
135
+ if (entries.length > MAX_VALUES)
136
+ throw invalid(`At most ${MAX_VALUES} ${field}.`, field);
137
+ for (const [name, value] of entries) {
138
+ if (!pattern.test(name))
139
+ throw invalid(`"${name}" is not a valid name.`, field);
140
+ if (value === null)
141
+ continue;
142
+ if (typeof value !== "string" || value.length > MAX_VALUE || /[\r\n\0]/.test(value)) {
143
+ throw invalid(`The value of ${name} must be one line of text.`, field);
144
+ }
145
+ }
146
+ }
147
+ /** A client to sign in with and scopes to ask for: one-line text values, at most 20 scopes. */
148
+ function checkOAuth(oauth) {
149
+ if (!oauth)
150
+ return null;
151
+ const line = (value, field) => {
152
+ if (value === undefined)
153
+ return undefined;
154
+ if (typeof value !== "string" || value.length > MAX_VALUE || /[\r\n\0]/.test(value)) {
155
+ throw invalid(`${field} must be one line of text.`, "oauth");
156
+ }
157
+ return value.trim() || undefined;
158
+ };
159
+ const clientId = line(oauth.clientId, "The client ID");
160
+ const clientSecret = line(oauth.clientSecret, "The client secret");
161
+ const scopes = oauth.scopes ?? [];
162
+ if (!Array.isArray(scopes) || scopes.length > 20)
163
+ throw invalid("At most 20 scopes.", "oauth");
164
+ for (const scope of scopes)
165
+ line(scope, "A scope");
166
+ return {
167
+ ...(clientId ? { clientId } : {}),
168
+ ...(clientSecret ? { clientSecret } : {}),
169
+ ...(scopes.length > 0 ? { scopes } : {}),
170
+ };
171
+ }
172
+ export function addMcpEntry(yewHome, input) {
173
+ if (!MCP_NAME.test(input.name)) {
174
+ throw invalid("The name uses letters, digits, dashes and underscores, up to 32.", "server");
175
+ }
176
+ const { doc, servers } = readFile(yewHome);
177
+ if (Object.hasOwn(servers, input.name)) {
178
+ throw conflict(`mcp.json already has a server named ${input.name}.`, undefined, "mcp-exists");
179
+ }
180
+ if (Object.keys(servers).length >= MAX_SERVERS) {
181
+ throw invalid(`Up to ${MAX_SERVERS} servers can be set up.`, "server");
182
+ }
183
+ const url = input.url?.trim();
184
+ const command = input.command?.trim();
185
+ const preset = input.preset?.trim();
186
+ if (preset && (url || command)) {
187
+ throw invalid("A preset takes neither a command nor a URL.", "preset");
188
+ }
189
+ if (!preset && Boolean(url) === Boolean(command)) {
190
+ throw invalid("Give either a command or a URL.", url ? "url" : "command");
191
+ }
192
+ let entry;
193
+ if (preset) {
194
+ if (!presetPackage(preset))
195
+ throw invalid(`Yew has no preset named ${preset}.`, "preset");
196
+ const env = input.env ?? {};
197
+ checkValues(env, ENV_NAME, "env");
198
+ entry = { preset, ...(Object.keys(env).length > 0 ? { env } : {}) };
199
+ }
200
+ else if (url) {
201
+ let parsed = null;
202
+ try {
203
+ parsed = new URL(url);
204
+ }
205
+ catch {
206
+ // Reported below.
207
+ }
208
+ if (!parsed || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
209
+ throw invalid("The URL must start with http:// or https://.", "url");
210
+ }
211
+ if (parsed.username || parsed.password) {
212
+ throw invalid("Put credentials in a header, not in the URL.", "url");
213
+ }
214
+ const headers = input.headers ?? {};
215
+ checkValues(headers, HEADER_NAME, "headers");
216
+ const oauth = checkOAuth(input.oauth);
217
+ entry = {
218
+ url,
219
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
220
+ ...(oauth ? { oauth } : {}),
221
+ };
222
+ }
223
+ else {
224
+ const args = input.args ?? [];
225
+ if (args.length > MAX_ARGS || args.some((arg) => arg.length > MAX_VALUE || /\0/.test(arg))) {
226
+ throw invalid(`Up to ${MAX_ARGS} arguments.`, "args");
227
+ }
228
+ if (command.length > 4096 || /[\r\n\0]/.test(command)) {
229
+ throw invalid("The command must be one line.", "command");
230
+ }
231
+ const env = input.env ?? {};
232
+ checkValues(env, ENV_NAME, "env");
233
+ entry = { command, args, ...(Object.keys(env).length > 0 ? { env } : {}) };
234
+ }
235
+ servers[input.name] = entry;
236
+ writeFile(yewHome, doc);
237
+ return view(input.name, entry);
238
+ }
239
+ function entryOf(servers, name) {
240
+ const entry = Object.hasOwn(servers, name) ? servers[name] : undefined;
241
+ if (!MCP_NAME.test(name) || !isObject(entry) || !view(name, entry)) {
242
+ throw notFound("MCP server", name);
243
+ }
244
+ return entry;
245
+ }
246
+ export function patchMcpEntry(yewHome, name, patch, builtin = {}) {
247
+ const { doc, servers } = readFile(yewHome);
248
+ if (builtin[name] && (!Object.hasOwn(servers, name) || turnsOff(servers[name]))) {
249
+ // One of Yew's own: the file only records that it is off.
250
+ if (patch.env || patch.headers) {
251
+ throw invalid("A server Yew sets up by itself has no variables to set.", "env");
252
+ }
253
+ if (patch.disabled === true)
254
+ servers[name] = { disabled: true };
255
+ else if (patch.disabled === false)
256
+ delete servers[name];
257
+ if (patch.disabled !== undefined)
258
+ writeFile(yewHome, doc);
259
+ return builtinView(name, builtin, turnsOff(servers[name]));
260
+ }
261
+ const entry = entryOf(servers, name);
262
+ const http = typeof entry.url === "string";
263
+ if (patch.disabled === true)
264
+ entry.disabled = true;
265
+ else if (patch.disabled === false)
266
+ delete entry.disabled;
267
+ const merge = (key, values) => {
268
+ const next = isObject(entry[key]) ? { ...entry[key] } : {};
269
+ for (const [field, value] of Object.entries(values)) {
270
+ if (value === null)
271
+ delete next[field];
272
+ else
273
+ next[field] = value;
274
+ }
275
+ if (Object.keys(next).length > MAX_VALUES)
276
+ throw invalid(`At most ${MAX_VALUES} ${key}.`, key);
277
+ if (Object.keys(next).length > 0)
278
+ entry[key] = next;
279
+ else
280
+ delete entry[key];
281
+ };
282
+ if (patch.env) {
283
+ if (http)
284
+ throw invalid("A server reached by URL takes headers, not variables.", "env");
285
+ checkValues(patch.env, ENV_NAME, "env");
286
+ merge("env", patch.env);
287
+ }
288
+ if (patch.headers) {
289
+ if (!http)
290
+ throw invalid("A server started by a command takes variables, not headers.", "headers");
291
+ checkValues(patch.headers, HEADER_NAME, "headers");
292
+ merge("headers", patch.headers);
293
+ }
294
+ writeFile(yewHome, doc);
295
+ return view(name, entry);
296
+ }
297
+ export function removeMcpEntry(yewHome, name, builtin = {}) {
298
+ const { doc, servers } = readFile(yewHome);
299
+ if (builtin[name] && (!Object.hasOwn(servers, name) || turnsOff(servers[name]))) {
300
+ throw conflict(`${name} is set up by Yew itself. It can be turned off, not removed.`, undefined, "mcp-builtin");
301
+ }
302
+ entryOf(servers, name);
303
+ delete servers[name];
304
+ writeFile(yewHome, doc);
305
+ }