@useavalon/caelence-agent 0.2.2-canary.3 → 0.2.2-canary.4

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.
@@ -88,6 +88,7 @@ import {
88
88
  import { FloatNotice } from "./FloatNotice";
89
89
  import { integrationMatches } from "./integration-search";
90
90
  import { LogoMark } from "./LogoMark";
91
+ import { McpPanel } from "./McpPanel";
91
92
  import { pickerKeyAction, pickerStartIndex, stepIndex } from "./picker-nav";
92
93
  import {
93
94
  enqueueMessage,
@@ -1935,6 +1936,45 @@ function IntegrationsPanel(
1935
1936
  bridge: BridgeClient;
1936
1937
  onNotice: (text: string) => void;
1937
1938
  }>,
1939
+ ): React.ReactElement {
1940
+ const [tab, setTab] = useState<"integrations" | "mcp">("integrations");
1941
+
1942
+ return (
1943
+ <div className="desk-integrations">
1944
+ <div className="desk-pane-tabs" role="tablist" aria-label="Integrations and MCP">
1945
+ <button
1946
+ type="button"
1947
+ role="tab"
1948
+ aria-selected={tab === "integrations"}
1949
+ className={tab === "integrations" ? "is-on" : undefined}
1950
+ onClick={() => setTab("integrations")}
1951
+ >
1952
+ Integrations
1953
+ </button>
1954
+ <button
1955
+ type="button"
1956
+ role="tab"
1957
+ aria-selected={tab === "mcp"}
1958
+ className={tab === "mcp" ? "is-on" : undefined}
1959
+ onClick={() => setTab("mcp")}
1960
+ >
1961
+ MCP
1962
+ </button>
1963
+ </div>
1964
+ {tab === "mcp" ? (
1965
+ <McpPanel bridge={props.bridge} onNotice={props.onNotice} />
1966
+ ) : (
1967
+ <HostedIntegrationsList bridge={props.bridge} onNotice={props.onNotice} />
1968
+ )}
1969
+ </div>
1970
+ );
1971
+ }
1972
+
1973
+ function HostedIntegrationsList(
1974
+ props: Readonly<{
1975
+ bridge: BridgeClient;
1976
+ onNotice: (text: string) => void;
1977
+ }>,
1938
1978
  ): React.ReactElement {
1939
1979
  const [items, setItems] = useState<PublicIntegration[] | null>(null);
1940
1980
  const [query, setQuery] = useState("");
@@ -1980,23 +2020,15 @@ function IntegrationsPanel(
1980
2020
  };
1981
2021
 
1982
2022
  if (!items && !loadFailed) {
1983
- return (
1984
- <div className="desk-integrations">
1985
- <p>Loading integrations</p>
1986
- </div>
1987
- );
2023
+ return <p>Loading integrations</p>;
1988
2024
  }
1989
2025
 
1990
2026
  if (!items && loadFailed) {
1991
- return (
1992
- <div className="desk-integrations">
1993
- <p className="desk-side-empty">Integrations could not be loaded</p>
1994
- </div>
1995
- );
2027
+ return <p className="desk-side-empty">Integrations could not be loaded</p>;
1996
2028
  }
1997
2029
 
1998
2030
  return (
1999
- <div className="desk-integrations">
2031
+ <>
2000
2032
  <p className="desk-integrations-lead">
2001
2033
  Hosted MCP servers the agent can call. App connectors for published sites stay in the
2002
2034
  builder.
@@ -2073,7 +2105,7 @@ function IntegrationsPanel(
2073
2105
  ) : null}
2074
2106
  </>
2075
2107
  )}
2076
- </div>
2108
+ </>
2077
2109
  );
2078
2110
  }
2079
2111
 
@@ -0,0 +1,268 @@
1
+ import { CheckIcon } from "@phosphor-icons/react/dist/csr/Check";
2
+ import { type ReactElement, useEffect, useState } from "react";
3
+ import { errorMessage } from "../../src/core/errors";
4
+ import { addMcp, type BridgeClient, getMcps, type PublicUserMcp, removeMcp } from "./api";
5
+
6
+ const LOCAL_MCP_PLACEHOLDER = `uvx mcp-server-fetch
7
+ or ------------------------
8
+ {
9
+ "mcpServers": {
10
+ "fetch": {
11
+ "command": "uvx",
12
+ "args": ["mcp-server-fetch"]
13
+ }
14
+ }
15
+ }`;
16
+
17
+ function mcpGlyph(item: PublicUserMcp): string {
18
+ if (item.kind === "http") return "URL";
19
+ const letters = item.label.replace(/[^a-zA-Z0-9]/g, "").slice(0, 2);
20
+ return letters.toUpperCase() || "MCP";
21
+ }
22
+
23
+ function mcpOrigin(item: PublicUserMcp): string {
24
+ if (item.origin === "config") return `${item.detail} · harness.config.ts`;
25
+ return item.detail;
26
+ }
27
+
28
+ function McpActions(
29
+ props: Readonly<{
30
+ item: PublicUserMcp;
31
+ pending: boolean;
32
+ onRemove: () => void;
33
+ }>,
34
+ ): ReactElement {
35
+ if (props.pending) {
36
+ return (
37
+ <span className="desk-integration-ok">
38
+ <span className="cel-chip__spin" aria-hidden="true" />
39
+ <span>Removing</span>
40
+ </span>
41
+ );
42
+ }
43
+ if (props.item.removable) {
44
+ return (
45
+ <button
46
+ type="button"
47
+ className="cel-btn cel-btn--quiet cel-btn--compact"
48
+ onClick={props.onRemove}
49
+ >
50
+ Remove
51
+ </button>
52
+ );
53
+ }
54
+ return (
55
+ <span className="desk-integration-ok">
56
+ <CheckIcon size={16} weight="regular" aria-hidden="true" />
57
+ In config
58
+ </span>
59
+ );
60
+ }
61
+
62
+ function McpRow(
63
+ props: Readonly<{
64
+ item: PublicUserMcp;
65
+ pending: boolean;
66
+ onRemove: () => void;
67
+ }>,
68
+ ): ReactElement {
69
+ const { item } = props;
70
+ return (
71
+ <li>
72
+ <span className="desk-integration-glyph desk-integration-mark" aria-hidden="true">
73
+ {mcpGlyph(item)}
74
+ </span>
75
+ <div>
76
+ <p>{item.label}</p>
77
+ <em>{mcpOrigin(item)}</em>
78
+ </div>
79
+ <div className="desk-integration-actions">
80
+ <McpActions item={item} pending={props.pending} onRemove={props.onRemove} />
81
+ </div>
82
+ </li>
83
+ );
84
+ }
85
+
86
+ export function McpPanel(
87
+ props: Readonly<{
88
+ bridge: BridgeClient;
89
+ onNotice: (text: string) => void;
90
+ }>,
91
+ ): ReactElement {
92
+ const [items, setItems] = useState<PublicUserMcp[] | null>(null);
93
+ const [loadFailed, setLoadFailed] = useState(false);
94
+ const [kind, setKind] = useState<"stdio" | "http">("stdio");
95
+ const [label, setLabel] = useState("");
96
+ const [command, setCommand] = useState("");
97
+ const [url, setUrl] = useState("");
98
+ const [token, setToken] = useState("");
99
+ const [busy, setBusy] = useState(false);
100
+ const [pendingId, setPendingId] = useState<string | null>(null);
101
+
102
+ useEffect(() => {
103
+ let alive = true;
104
+ void getMcps(props.bridge)
105
+ .then((result) => {
106
+ if (alive) setItems(result.items);
107
+ })
108
+ .catch((err: unknown) => {
109
+ if (!alive) return;
110
+ setLoadFailed(true);
111
+ props.onNotice(errorMessage(err));
112
+ });
113
+ return () => {
114
+ alive = false;
115
+ };
116
+ }, [props.bridge, props.onNotice]);
117
+
118
+ const submit = async (): Promise<void> => {
119
+ setBusy(true);
120
+ try {
121
+ const result = await addMcp(
122
+ props.bridge,
123
+ kind === "http"
124
+ ? { kind: "http", label: label.trim() || undefined, url: url.trim(), token: token.trim() }
125
+ : { kind: "stdio", label: label.trim() || undefined, command: command.trim() },
126
+ );
127
+ setItems(result.items);
128
+ setLabel("");
129
+ setCommand("");
130
+ setUrl("");
131
+ setToken("");
132
+ } catch (err) {
133
+ props.onNotice(errorMessage(err));
134
+ } finally {
135
+ setBusy(false);
136
+ }
137
+ };
138
+
139
+ const drop = async (id: string): Promise<void> => {
140
+ setPendingId(id);
141
+ try {
142
+ const result = await removeMcp(props.bridge, id);
143
+ setItems(result.items);
144
+ } catch (err) {
145
+ props.onNotice(errorMessage(err));
146
+ } finally {
147
+ setPendingId(null);
148
+ }
149
+ };
150
+
151
+ if (!items && !loadFailed) {
152
+ return <p>Loading MCP servers</p>;
153
+ }
154
+
155
+ if (!items && loadFailed) {
156
+ return <p className="desk-side-empty">MCP servers could not be loaded</p>;
157
+ }
158
+
159
+ const listed = items ?? [];
160
+ const canAdd = kind === "http" ? url.trim().length > 0 : command.trim().length > 0;
161
+
162
+ return (
163
+ <>
164
+ <p className="desk-integrations-lead">
165
+ Local command or URL MCP servers for this project. Paste a command, or an mcpServers JSON
166
+ block.
167
+ </p>
168
+ <div className="desk-pane-tabs desk-pane-tabs--compact" role="tablist" aria-label="MCP kind">
169
+ <button
170
+ type="button"
171
+ role="tab"
172
+ aria-selected={kind === "stdio"}
173
+ className={kind === "stdio" ? "is-on" : undefined}
174
+ onClick={() => setKind("stdio")}
175
+ >
176
+ Local
177
+ </button>
178
+ <button
179
+ type="button"
180
+ role="tab"
181
+ aria-selected={kind === "http"}
182
+ className={kind === "http" ? "is-on" : undefined}
183
+ onClick={() => setKind("http")}
184
+ >
185
+ URL
186
+ </button>
187
+ </div>
188
+ <form
189
+ className="desk-mcp-form"
190
+ onSubmit={(event) => {
191
+ event.preventDefault();
192
+ if (canAdd && !busy) void submit();
193
+ }}
194
+ >
195
+ <label>
196
+ <span>Name</span>
197
+ <input
198
+ className="cel-input"
199
+ value={label}
200
+ placeholder="Optional"
201
+ onChange={(event) => setLabel(event.target.value)}
202
+ />
203
+ </label>
204
+ {kind === "http" ? (
205
+ <>
206
+ <label>
207
+ <span>Server URL</span>
208
+ <input
209
+ className="cel-input"
210
+ value={url}
211
+ placeholder="http://127.0.0.1:3100/mcp"
212
+ autoComplete="off"
213
+ spellCheck={false}
214
+ onChange={(event) => setUrl(event.target.value)}
215
+ />
216
+ </label>
217
+ <label>
218
+ <span>Bearer token</span>
219
+ <input
220
+ className="cel-input"
221
+ type="password"
222
+ value={token}
223
+ placeholder="Optional"
224
+ autoComplete="off"
225
+ spellCheck={false}
226
+ onChange={(event) => setToken(event.target.value)}
227
+ />
228
+ </label>
229
+ </>
230
+ ) : (
231
+ <label>
232
+ <span>Command</span>
233
+ <textarea
234
+ className="cel-input"
235
+ rows={8}
236
+ value={command}
237
+ placeholder={LOCAL_MCP_PLACEHOLDER}
238
+ autoComplete="off"
239
+ spellCheck={false}
240
+ onChange={(event) => setCommand(event.target.value)}
241
+ />
242
+ </label>
243
+ )}
244
+ <button
245
+ type="submit"
246
+ className="cel-btn cel-btn--secondary cel-btn--compact"
247
+ disabled={!canAdd || busy}
248
+ >
249
+ {busy ? "Adding" : "Add"}
250
+ </button>
251
+ </form>
252
+ {listed.length === 0 ? (
253
+ <p className="desk-side-empty">No MCP servers yet. Add a local command or a URL.</p>
254
+ ) : (
255
+ <ul className="desk-integration-list">
256
+ {listed.map((item) => (
257
+ <McpRow
258
+ key={item.id}
259
+ item={item}
260
+ pending={pendingId === item.id}
261
+ onRemove={() => void drop(item.id)}
262
+ />
263
+ ))}
264
+ </ul>
265
+ )}
266
+ </>
267
+ );
268
+ }
@@ -250,6 +250,48 @@ export function disconnectIntegration(
250
250
  });
251
251
  }
252
252
 
253
+ export interface PublicUserMcp {
254
+ id: string;
255
+ label: string;
256
+ kind: "stdio" | "http";
257
+ detail: string;
258
+ origin: "user" | "config";
259
+ removable: boolean;
260
+ }
261
+
262
+ export interface AddMcpInput {
263
+ label?: string;
264
+ kind: "stdio" | "http";
265
+ command?: string;
266
+ args?: string;
267
+ url?: string;
268
+ token?: string;
269
+ }
270
+
271
+ export function getMcps(bridge: BridgeClient): Promise<{ items: PublicUserMcp[] }> {
272
+ return request(bridge, "/mcp");
273
+ }
274
+
275
+ export function addMcp(
276
+ bridge: BridgeClient,
277
+ input: AddMcpInput,
278
+ ): Promise<{ ok: boolean; items: PublicUserMcp[] }> {
279
+ return request(bridge, "/mcp/add", {
280
+ method: "POST",
281
+ body: JSON.stringify(input),
282
+ });
283
+ }
284
+
285
+ export function removeMcp(
286
+ bridge: BridgeClient,
287
+ id: string,
288
+ ): Promise<{ ok: boolean; items: PublicUserMcp[] }> {
289
+ return request(bridge, "/mcp/remove", {
290
+ method: "POST",
291
+ body: JSON.stringify({ id }),
292
+ });
293
+ }
294
+
253
295
  export function openUrl(bridge: BridgeClient, url: string): Promise<{ ok: boolean }> {
254
296
  return request(bridge, "/open", {
255
297
  method: "POST",
@@ -1630,6 +1630,75 @@ p.desk-line__caption {
1630
1630
  gap: 12px;
1631
1631
  }
1632
1632
 
1633
+ .desk-pane-tabs {
1634
+ display: flex;
1635
+ align-self: start;
1636
+ gap: 2px;
1637
+ padding: 3px;
1638
+ border-radius: var(--r-lg);
1639
+ background: var(--bg-inset);
1640
+ }
1641
+
1642
+ .desk-pane-tabs button {
1643
+ margin: 0;
1644
+ padding: 6px 12px;
1645
+ border: 0;
1646
+ border-radius: var(--r-md);
1647
+ background: transparent;
1648
+ color: var(--text-secondary);
1649
+ font: inherit;
1650
+ font-size: 13px;
1651
+ font-weight: 600;
1652
+ line-height: 1.2;
1653
+ cursor: pointer;
1654
+ }
1655
+
1656
+ .desk-pane-tabs button.is-on {
1657
+ background: var(--card);
1658
+ color: var(--text);
1659
+ box-shadow: 0 1px 2px color-mix(in srgb, var(--ink) 14%, transparent);
1660
+ }
1661
+
1662
+ .desk-pane-tabs button:focus-visible {
1663
+ outline: 1.5px solid var(--measure);
1664
+ outline-offset: 1px;
1665
+ }
1666
+
1667
+ .desk-pane-tabs--compact button {
1668
+ padding: 5px 10px;
1669
+ font-weight: 500;
1670
+ }
1671
+
1672
+ .desk-mcp-form {
1673
+ display: flex;
1674
+ flex-direction: column;
1675
+ gap: 10px;
1676
+ }
1677
+
1678
+ .desk-mcp-form label {
1679
+ display: flex;
1680
+ flex-direction: column;
1681
+ gap: 6px;
1682
+ }
1683
+
1684
+ .desk-mcp-form label > span:first-child {
1685
+ font-weight: 600;
1686
+ }
1687
+
1688
+ .desk-mcp-form .cel-btn {
1689
+ align-self: flex-start;
1690
+ }
1691
+
1692
+ .desk-mcp-form textarea.cel-input {
1693
+ height: auto;
1694
+ min-height: 148px;
1695
+ padding-top: 8px;
1696
+ padding-bottom: 8px;
1697
+ resize: vertical;
1698
+ line-height: 1.45;
1699
+ font-family: var(--mono);
1700
+ }
1701
+
1633
1702
  .desk-integrations-lead {
1634
1703
  margin: 0;
1635
1704
  color: var(--text-secondary);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useavalon/caelence-agent",
3
- "version": "0.2.2-canary.3",
3
+ "version": "0.2.2-canary.4",
4
4
  "description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -58,6 +58,7 @@ function fakeHarness(overrides: Partial<HarnessRuntime> = {}): HarnessRuntime {
58
58
  disabledSkills: () => [],
59
59
  enableSkill: () => ({ ok: true }),
60
60
  reloadIntegrations: async () => {},
61
+ reloadExtraMcp: async () => {},
61
62
  chat: async () => "",
62
63
  observability: {} as HarnessRuntime["observability"],
63
64
  close() {},
@@ -21,6 +21,12 @@ import {
21
21
  } from "../integrations/connect.ts";
22
22
  import { readProviderOAuth, writeProviderOAuth } from "../integrations/oauth-clients.ts";
23
23
  import { listPublicIntegrations, removeConnection } from "../integrations/store.ts";
24
+ import {
25
+ type AddUserMcpInput,
26
+ addUserMcpServer,
27
+ listPublicMcps,
28
+ removeUserMcpServer,
29
+ } from "../mcp/user-servers.ts";
24
30
  import { transcribeAudio } from "../media/openrouter-generate.ts";
25
31
  import { readMediaPrefs } from "../media/prefs.ts";
26
32
  import { PRODUCT_NAME } from "../product.ts";
@@ -385,6 +391,31 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
385
391
  return json({ ok: true, items: listPublicIntegrations() });
386
392
  };
387
393
 
394
+ const mcpPage = () => ({ items: listPublicMcps(harness.cwd, harness.config.mcp) });
395
+
396
+ const route_get_mcp = async (_req: Request, _url: URL): Promise<Response> => {
397
+ return json(mcpPage());
398
+ };
399
+
400
+ const route_post_mcp_add = async (req: Request, _url: URL): Promise<Response> => {
401
+ const body = (await readJson(req)) as AddUserMcpInput;
402
+ const added = addUserMcpServer(harness.cwd, body, harness.config.mcp);
403
+ if ("error" in added) return json({ error: added.error }, 400);
404
+ await harness.reloadExtraMcp();
405
+ return json({ ok: true, ...mcpPage() });
406
+ };
407
+
408
+ const route_post_mcp_remove = async (req: Request, _url: URL): Promise<Response> => {
409
+ const body = await readJson(req);
410
+ const id = typeof body.id === "string" ? body.id.trim() : "";
411
+ if (!id) return json({ error: "id is required." }, 400);
412
+ if (!removeUserMcpServer(harness.cwd, id)) {
413
+ return json({ error: "MCP not found." }, 400);
414
+ }
415
+ await harness.reloadExtraMcp();
416
+ return json({ ok: true, ...mcpPage() });
417
+ };
418
+
388
419
  const skillsPage = (popular = cachedPopularSkills()) =>
389
420
  buildSkillsPage(
390
421
  withDisabledCatalogSkills(harness.skills, harness.disabledSkills()),
@@ -780,6 +811,9 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
780
811
  "GET /integrations": route_get_integrations,
781
812
  "POST /integrations/connect": route_post_integrations_connect,
782
813
  "POST /integrations/disconnect": route_post_integrations_disconnect,
814
+ "GET /mcp": route_get_mcp,
815
+ "POST /mcp/add": route_post_mcp_add,
816
+ "POST /mcp/remove": route_post_mcp_remove,
783
817
  "GET /skills": route_get_skills,
784
818
  "GET /skills/popular": route_get_skills_popular,
785
819
  "GET /skills/search": route_get_skills_search,
@@ -0,0 +1,138 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ addUserMcpServer,
7
+ isHttpMcpUrl,
8
+ listPublicMcps,
9
+ listUserMcpServers,
10
+ parseAddUserMcp,
11
+ parseMcpServersJson,
12
+ removeUserMcpServer,
13
+ splitMcpArgs,
14
+ userMcpPath,
15
+ userMcpToolPrefix,
16
+ } from "./user-servers.ts";
17
+
18
+ describe("user MCP servers", () => {
19
+ test("splits quoted command args", () => {
20
+ expect(splitMcpArgs(`npx -y "@ag-grid/mcp-server"`)).toEqual([
21
+ "npx",
22
+ "-y",
23
+ "@ag-grid/mcp-server",
24
+ ]);
25
+ });
26
+
27
+ test("accepts http MCP urls only", () => {
28
+ expect(isHttpMcpUrl("https://mcp.example.com/mcp")).toBe(true);
29
+ expect(isHttpMcpUrl("http://127.0.0.1:3100/mcp")).toBe(true);
30
+ expect(isHttpMcpUrl("file:///tmp/mcp")).toBe(false);
31
+ expect(isHttpMcpUrl("javascript:alert(1)")).toBe(false);
32
+ });
33
+
34
+ test("namespaces user tools away from hosted connectors", () => {
35
+ expect(userMcpToolPrefix("ag-grid")).toBe("mcp_ag_grid");
36
+ });
37
+
38
+ test("parses a pasted local command into argv", () => {
39
+ const parsed = parseAddUserMcp({ command: "npx -y @ag-grid/mcp-server", label: "AG Grid" }, []);
40
+ expect(parsed).toEqual({
41
+ ok: {
42
+ id: "ag-grid",
43
+ label: "AG Grid",
44
+ kind: "stdio",
45
+ command: "npx",
46
+ args: ["-y", "@ag-grid/mcp-server"],
47
+ },
48
+ });
49
+ });
50
+
51
+ test("round-trips a local server and hides tokens on the public list", async () => {
52
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mcp-"));
53
+ try {
54
+ const added = addUserMcpServer(cwd, {
55
+ kind: "http",
56
+ url: "https://mcp.example.com/mcp",
57
+ token: "secret-token",
58
+ label: "Example",
59
+ });
60
+ expect("ok" in added).toBe(true);
61
+ const stored = listUserMcpServers(cwd);
62
+ expect(stored[0]?.token).toBe("secret-token");
63
+ const listed = listPublicMcps(cwd, [{ command: "uvx", args: ["demo-mcp"] }]);
64
+ expect(listed.map((item) => item.id)).toEqual(["example", "config-0"]);
65
+ expect(listed[0]?.detail).toBe("https://mcp.example.com/mcp · token set");
66
+ expect(JSON.stringify(listed)).not.toContain("secret-token");
67
+ expect(listed[1]?.removable).toBe(false);
68
+ const raw = await readFile(userMcpPath(cwd), "utf8");
69
+ expect(raw).toContain("secret-token");
70
+ expect(removeUserMcpServer(cwd, "example")).toBe(true);
71
+ expect(listUserMcpServers(cwd)).toEqual([]);
72
+ expect(removeUserMcpServer(cwd, "config-0")).toBe(false);
73
+ } finally {
74
+ await rm(cwd, { recursive: true, force: true });
75
+ }
76
+ });
77
+
78
+ test("parses a pasted mcpServers JSON block", () => {
79
+ const parsed = parseMcpServersJson(`{
80
+ "mcpServers": {
81
+ "fetch": {
82
+ "command": "uvx",
83
+ "args": ["mcp-server-fetch"],
84
+ "env": {},
85
+ "disabled": true,
86
+ "autoApprove": []
87
+ }
88
+ }
89
+ }`);
90
+ expect(parsed).toEqual({
91
+ ok: [
92
+ {
93
+ kind: "stdio",
94
+ label: "fetch",
95
+ command: "uvx",
96
+ args: ["mcp-server-fetch"],
97
+ },
98
+ ],
99
+ });
100
+ });
101
+
102
+ test("adds a pasted mcpServers JSON block", async () => {
103
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mcp-json-"));
104
+ try {
105
+ const added = addUserMcpServer(cwd, {
106
+ kind: "stdio",
107
+ command: `{
108
+ "mcpServers": {
109
+ "fetch": {
110
+ "command": "uvx",
111
+ "args": ["mcp-server-fetch"]
112
+ }
113
+ }
114
+ }`,
115
+ });
116
+ expect(added).toMatchObject({
117
+ ok: {
118
+ label: "fetch",
119
+ kind: "stdio",
120
+ command: "uvx",
121
+ args: ["mcp-server-fetch"],
122
+ },
123
+ });
124
+ expect(listUserMcpServers(cwd)[0]?.command).toBe("uvx");
125
+ } finally {
126
+ await rm(cwd, { recursive: true, force: true });
127
+ }
128
+ });
129
+
130
+ test("rejects a duplicate command already in harness.config.ts", () => {
131
+ const parsed = parseAddUserMcp(
132
+ { command: "uvx", args: ["demo-mcp"] },
133
+ [],
134
+ [{ command: "uvx", args: ["demo-mcp"] }],
135
+ );
136
+ expect(parsed).toEqual({ error: "That MCP is already in harness.config.ts." });
137
+ });
138
+ });
@@ -0,0 +1,427 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import type { ExtraMcpServerConfig } from "../config.ts";
4
+
5
+ export type UserMcpKind = "stdio" | "http";
6
+
7
+ export interface UserMcpServer {
8
+ id: string;
9
+ label: string;
10
+ kind: UserMcpKind;
11
+ command?: string;
12
+ args?: string[];
13
+ env?: Record<string, string>;
14
+ url?: string;
15
+ token?: string;
16
+ }
17
+
18
+ export interface PublicUserMcp {
19
+ id: string;
20
+ label: string;
21
+ kind: UserMcpKind;
22
+ detail: string;
23
+ origin: "user" | "config";
24
+ removable: boolean;
25
+ }
26
+
27
+ export interface AddUserMcpInput {
28
+ label?: string;
29
+ kind?: string;
30
+ command?: string;
31
+ args?: string | string[];
32
+ url?: string;
33
+ token?: string;
34
+ env?: Record<string, string>;
35
+ }
36
+
37
+ interface StoreFile {
38
+ servers: UserMcpServer[];
39
+ }
40
+
41
+ export function userMcpPath(cwd: string): string {
42
+ return resolve(cwd, ".harness", "mcp.json");
43
+ }
44
+
45
+ export function userMcpToolPrefix(id: string): string {
46
+ const slug = id.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
47
+ return `mcp_${slug || "server"}`;
48
+ }
49
+
50
+ export function splitMcpArgs(raw: string): string[] {
51
+ const out: string[] = [];
52
+ const re = /"([^"]*)"|'([^']*)'|[^\s]+/g;
53
+ for (const match of raw.matchAll(re)) {
54
+ const part = match[1] ?? match[2] ?? match[0];
55
+ if (part) out.push(part);
56
+ }
57
+ return out;
58
+ }
59
+
60
+ export function isHttpMcpUrl(value: string): boolean {
61
+ try {
62
+ const url = new URL(value);
63
+ return url.protocol === "http:" || url.protocol === "https:";
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ function looksLikeJsonObject(raw: string): boolean {
70
+ const trimmed = raw.trim();
71
+ return trimmed.startsWith("{") && trimmed.endsWith("}");
72
+ }
73
+
74
+ function tokenFromHeaders(value: unknown): string | undefined {
75
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
76
+ const headers = value as Record<string, unknown>;
77
+ const auth = headers.Authorization ?? headers.authorization;
78
+ if (typeof auth !== "string") return undefined;
79
+ return auth.replace(/^Bearer\s+/i, "").trim() || undefined;
80
+ }
81
+
82
+ function mcpEntryToInput(name: string, value: unknown): AddUserMcpInput | { error: string } {
83
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
84
+ return { error: "MCP server config is not valid." };
85
+ }
86
+ const row = value as Record<string, unknown>;
87
+ const label =
88
+ name.trim() || (typeof row.name === "string" ? row.name.trim() : undefined) || undefined;
89
+ const url =
90
+ typeof row.url === "string"
91
+ ? row.url.trim()
92
+ : typeof row.serverUrl === "string"
93
+ ? row.serverUrl.trim()
94
+ : "";
95
+ if (url) {
96
+ const token =
97
+ (typeof row.token === "string" ? row.token.trim() : "") || tokenFromHeaders(row.headers);
98
+ return { kind: "http", ...(label ? { label } : {}), url, ...(token ? { token } : {}) };
99
+ }
100
+ const command = typeof row.command === "string" ? row.command.trim() : "";
101
+ if (!command) {
102
+ return { error: `${label || "MCP"} needs a command or URL.` };
103
+ }
104
+ const args = Array.isArray(row.args)
105
+ ? row.args.filter((part): part is string => typeof part === "string")
106
+ : [];
107
+ const env = asEnv(row.env);
108
+ return {
109
+ kind: "stdio",
110
+ ...(label ? { label } : {}),
111
+ command,
112
+ ...(args.length > 0 ? { args } : {}),
113
+ ...(env ? { env } : {}),
114
+ };
115
+ }
116
+
117
+ function mcpServerMap(value: unknown): Record<string, unknown> | undefined {
118
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
119
+ return value as Record<string, unknown>;
120
+ }
121
+
122
+ export function parseMcpServersJson(raw: string): { ok: AddUserMcpInput[] } | { error: string } {
123
+ let parsed: unknown;
124
+ try {
125
+ parsed = JSON.parse(raw) as unknown;
126
+ } catch {
127
+ return { error: "MCP JSON is not valid." };
128
+ }
129
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
130
+ return { error: "MCP JSON needs a command, URL, or mcpServers map." };
131
+ }
132
+ const row = parsed as Record<string, unknown>;
133
+ const grouped = mcpServerMap(row.mcpServers) ?? mcpServerMap(row.servers);
134
+ const entries = grouped
135
+ ? Object.entries(grouped)
136
+ : typeof row.command === "string" ||
137
+ typeof row.url === "string" ||
138
+ typeof row.serverUrl === "string"
139
+ ? [["", parsed] as [string, unknown]]
140
+ : [];
141
+ if (entries.length === 0) {
142
+ return { error: "MCP JSON needs a command, URL, or mcpServers map." };
143
+ }
144
+ const out: AddUserMcpInput[] = [];
145
+ for (const [name, value] of entries) {
146
+ const input = mcpEntryToInput(name, value);
147
+ if ("error" in input) return input;
148
+ out.push(input);
149
+ }
150
+ return { ok: out };
151
+ }
152
+
153
+ export function expandMcpAddInput(
154
+ raw: AddUserMcpInput,
155
+ ): { ok: AddUserMcpInput[] } | { error: string } {
156
+ const command = typeof raw.command === "string" ? raw.command.trim() : "";
157
+ if (!looksLikeJsonObject(command)) return { ok: [raw] };
158
+ const parsed = parseMcpServersJson(command);
159
+ if ("error" in parsed) return parsed;
160
+ if (raw.label?.trim() && parsed.ok.length === 1) {
161
+ const first = parsed.ok[0];
162
+ if (first && !first.label) return { ok: [{ ...first, label: raw.label.trim() }] };
163
+ }
164
+ return parsed;
165
+ }
166
+
167
+ function readStore(cwd: string): StoreFile {
168
+ const path = userMcpPath(cwd);
169
+ if (!existsSync(path)) return { servers: [] };
170
+ try {
171
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as StoreFile;
172
+ if (!parsed || !Array.isArray(parsed.servers)) return { servers: [] };
173
+ return { servers: parsed.servers.filter(isUserMcpServer) };
174
+ } catch {
175
+ return { servers: [] };
176
+ }
177
+ }
178
+
179
+ function isUserMcpServer(value: unknown): value is UserMcpServer {
180
+ if (!value || typeof value !== "object") return false;
181
+ const row = value as Record<string, unknown>;
182
+ if (typeof row.id !== "string" || !row.id.trim()) return false;
183
+ if (typeof row.label !== "string" || !row.label.trim()) return false;
184
+ if (row.kind === "stdio") {
185
+ return typeof row.command === "string" && row.command.trim().length > 0;
186
+ }
187
+ if (row.kind === "http") {
188
+ return typeof row.url === "string" && isHttpMcpUrl(row.url.trim());
189
+ }
190
+ return false;
191
+ }
192
+
193
+ function writeStore(cwd: string, store: StoreFile): void {
194
+ const path = userMcpPath(cwd);
195
+ mkdirSync(dirname(path), { recursive: true });
196
+ writeFileSync(path, `${JSON.stringify(store, null, "\t")}\n`, { encoding: "utf8", mode: 0o600 });
197
+ try {
198
+ chmodSync(path, 0o600);
199
+ } catch {
200
+ // best-effort on filesystems that ignore mode
201
+ }
202
+ }
203
+
204
+ export function listUserMcpServers(cwd: string): UserMcpServer[] {
205
+ return readStore(cwd).servers;
206
+ }
207
+
208
+ function slugMcpId(label: string, existing: string[]): string {
209
+ const base =
210
+ label
211
+ .trim()
212
+ .toLowerCase()
213
+ .replace(/[^a-z0-9]+/g, "-")
214
+ .replace(/^-+|-+$/g, "")
215
+ .slice(0, 40) || "mcp";
216
+ const taken = new Set(existing);
217
+ if (!taken.has(base) && !base.startsWith("config-")) return base;
218
+ let n = 2;
219
+ while (taken.has(`${base}-${n}`)) n += 1;
220
+ return `${base}-${n}`;
221
+ }
222
+
223
+ function asStringList(value: string | string[] | undefined): string[] {
224
+ if (Array.isArray(value)) {
225
+ return value.map((part) => part.trim()).filter(Boolean);
226
+ }
227
+ if (typeof value === "string") return splitMcpArgs(value);
228
+ return [];
229
+ }
230
+
231
+ function asEnv(value: unknown): Record<string, string> | undefined {
232
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
233
+ const out: Record<string, string> = {};
234
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
235
+ if (!key.trim() || typeof entry !== "string") continue;
236
+ out[key] = entry;
237
+ }
238
+ return Object.keys(out).length > 0 ? out : undefined;
239
+ }
240
+
241
+ function defaultLabel(kind: UserMcpKind, command: string, args: string[], url: string): string {
242
+ if (kind === "http") {
243
+ try {
244
+ return new URL(url).hostname || "MCP";
245
+ } catch {
246
+ return "MCP";
247
+ }
248
+ }
249
+ const pkg = args.find((part) => part.startsWith("@") || part.toLowerCase().includes("mcp"));
250
+ return pkg ?? command;
251
+ }
252
+
253
+ function stdioFingerprint(command: string, args: string[]): string {
254
+ return `stdio:${command}\0${args.join("\0")}`;
255
+ }
256
+
257
+ function httpFingerprint(url: string): string {
258
+ return `http:${url}`;
259
+ }
260
+
261
+ function configFingerprints(configMcp: ExtraMcpServerConfig[]): Set<string> {
262
+ return new Set(configMcp.map((mcp) => stdioFingerprint(mcp.command, mcp.args ?? [])));
263
+ }
264
+
265
+ function parseMcpKind(raw: string | undefined): UserMcpKind | null {
266
+ if (!raw || raw === "stdio") return "stdio";
267
+ if (raw === "http") return "http";
268
+ return null;
269
+ }
270
+
271
+ export function parseAddUserMcp(
272
+ raw: AddUserMcpInput,
273
+ existing: UserMcpServer[],
274
+ configMcp: ExtraMcpServerConfig[] = [],
275
+ ): { ok: UserMcpServer } | { error: string } {
276
+ const kind = parseMcpKind(raw.kind);
277
+ if (!kind) return { error: "kind must be stdio or http." };
278
+
279
+ if (kind === "http") {
280
+ const url = typeof raw.url === "string" ? raw.url.trim() : "";
281
+ if (!url) return { error: "URL is required." };
282
+ if (!isHttpMcpUrl(url)) return { error: "URL must be http or https." };
283
+ const token = typeof raw.token === "string" ? raw.token.trim() : "";
284
+ const print = httpFingerprint(url);
285
+ if (
286
+ existing.some(
287
+ (server) => server.kind === "http" && httpFingerprint(server.url ?? "") === print,
288
+ )
289
+ ) {
290
+ return { error: "That MCP is already added." };
291
+ }
292
+ const label =
293
+ (typeof raw.label === "string" ? raw.label.trim() : "") || defaultLabel("http", "", [], url);
294
+ const id = slugMcpId(
295
+ label,
296
+ existing.map((server) => server.id),
297
+ );
298
+ return {
299
+ ok: {
300
+ id,
301
+ label,
302
+ kind: "http",
303
+ url,
304
+ ...(token ? { token } : {}),
305
+ },
306
+ };
307
+ }
308
+
309
+ const givenCommand = typeof raw.command === "string" ? raw.command.trim() : "";
310
+ if (!givenCommand) return { error: "Command is required." };
311
+ let command = givenCommand;
312
+ let args = asStringList(raw.args);
313
+ if (args.length === 0 && command.includes(" ")) {
314
+ const parts = splitMcpArgs(command);
315
+ command = parts[0] ?? "";
316
+ args = parts.slice(1);
317
+ }
318
+ if (!command) return { error: "Command is required." };
319
+ if (command.includes("\0") || args.some((part) => part.includes("\0"))) {
320
+ return { error: "Command is not valid." };
321
+ }
322
+
323
+ const print = stdioFingerprint(command, args);
324
+ if (configFingerprints(configMcp).has(print)) {
325
+ return { error: "That MCP is already in harness.config.ts." };
326
+ }
327
+ if (
328
+ existing.some(
329
+ (server) =>
330
+ server.kind === "stdio" &&
331
+ stdioFingerprint(server.command ?? "", server.args ?? []) === print,
332
+ )
333
+ ) {
334
+ return { error: "That MCP is already added." };
335
+ }
336
+
337
+ const env = asEnv(raw.env);
338
+ const label =
339
+ (typeof raw.label === "string" ? raw.label.trim() : "") ||
340
+ defaultLabel("stdio", command, args, "");
341
+ const id = slugMcpId(
342
+ label,
343
+ existing.map((server) => server.id),
344
+ );
345
+ return {
346
+ ok: {
347
+ id,
348
+ label,
349
+ kind: "stdio",
350
+ command,
351
+ ...(args.length > 0 ? { args } : {}),
352
+ ...(env ? { env } : {}),
353
+ },
354
+ };
355
+ }
356
+
357
+ export function addUserMcpServer(
358
+ cwd: string,
359
+ raw: AddUserMcpInput,
360
+ configMcp: ExtraMcpServerConfig[] = [],
361
+ ): { ok: UserMcpServer } | { error: string } {
362
+ const expanded = expandMcpAddInput(raw);
363
+ if ("error" in expanded) return expanded;
364
+ const store = readStore(cwd);
365
+ let existing = store.servers;
366
+ const added: UserMcpServer[] = [];
367
+ let lastError: string | undefined;
368
+ for (const input of expanded.ok) {
369
+ const parsed = parseAddUserMcp(input, existing, configMcp);
370
+ if ("error" in parsed) {
371
+ lastError = parsed.error;
372
+ continue;
373
+ }
374
+ existing = [...existing, parsed.ok];
375
+ added.push(parsed.ok);
376
+ }
377
+ if (added.length === 0) return { error: lastError ?? "No MCP servers to add." };
378
+ writeStore(cwd, { servers: existing });
379
+ const last = added[added.length - 1];
380
+ if (!last) return { error: lastError ?? "No MCP servers to add." };
381
+ return { ok: last };
382
+ }
383
+
384
+ export function removeUserMcpServer(cwd: string, id: string): boolean {
385
+ const key = id.trim();
386
+ if (!key || key.startsWith("config-")) return false;
387
+ const store = readStore(cwd);
388
+ const next = store.servers.filter((server) => server.id !== key);
389
+ if (next.length === store.servers.length) return false;
390
+ writeStore(cwd, { servers: next });
391
+ return true;
392
+ }
393
+
394
+ function publicDetail(server: UserMcpServer): string {
395
+ if (server.kind === "http") {
396
+ const url = server.url ?? "";
397
+ return server.token ? `${url} · token set` : url;
398
+ }
399
+ return [server.command, ...(server.args ?? [])].filter(Boolean).join(" ");
400
+ }
401
+
402
+ export function toPublicUserMcp(server: UserMcpServer): PublicUserMcp {
403
+ return {
404
+ id: server.id,
405
+ label: server.label,
406
+ kind: server.kind,
407
+ detail: publicDetail(server),
408
+ origin: "user",
409
+ removable: true,
410
+ };
411
+ }
412
+
413
+ export function listPublicMcps(
414
+ cwd: string,
415
+ configMcp: ExtraMcpServerConfig[] = [],
416
+ ): PublicUserMcp[] {
417
+ const user = listUserMcpServers(cwd).map(toPublicUserMcp);
418
+ const config = configMcp.map((mcp, index) => ({
419
+ id: `config-${index}`,
420
+ label: mcp.command,
421
+ kind: "stdio" as const,
422
+ detail: [mcp.command, ...(mcp.args ?? [])].filter(Boolean).join(" "),
423
+ origin: "config" as const,
424
+ removable: false,
425
+ }));
426
+ return [...user, ...config];
427
+ }
package/src/runtime.ts CHANGED
@@ -40,6 +40,7 @@ import { addUsage, type TokenUsage } from "./core/usage.ts";
40
40
  import { type ChatFn, createOpenRouterChat } from "./evals/runner.ts";
41
41
  import { buildRemoteMcpTools } from "./integrations/remote-mcp.ts";
42
42
  import { linkedMcpSources } from "./integrations/store.ts";
43
+ import { listUserMcpServers, userMcpToolPrefix } from "./mcp/user-servers.ts";
43
44
  import { createObservability } from "./observability/create.ts";
44
45
  import { noopObservability } from "./observability/noop.ts";
45
46
  import { harnessPromptRecords, syncPrompts } from "./observability/prompts.ts";
@@ -105,6 +106,7 @@ export interface HarnessRuntime {
105
106
  compact(): Promise<boolean>;
106
107
  reloadSkills(): Skill[];
107
108
  reloadIntegrations(): Promise<void>;
109
+ reloadExtraMcp(): Promise<void>;
108
110
  integrationIds(): string[];
109
111
  authorSkill(name: string, brief: string): Promise<{ rel: string } | { error: string }>;
110
112
  findSkills(query: string): Promise<string>;
@@ -174,8 +176,9 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
174
176
  const todos = createMemoryTodoStore();
175
177
  const hooks = createHookRunner({ cwd, hooks: config.hooks });
176
178
  void hooks.sessionStart();
177
- const closers: Array<() => void> = [];
178
179
  const extra: McpToolDefinition[] = [...(options.extraTools ?? [])];
180
+ let extraMcpTools: McpToolDefinition[] = [];
181
+ let extraMcpClosers: Array<() => void> = [];
179
182
  let integrationTools: McpToolDefinition[] = [];
180
183
  const shouldLoadIntegrations = options.loadIntegrations ?? !options.provider;
181
184
  const reloadIntegrations = async (): Promise<void> => {
@@ -185,16 +188,53 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
185
188
  }
186
189
  integrationTools = await buildRemoteMcpTools({ sources: linkedMcpSources() });
187
190
  };
188
- await reloadIntegrations();
189
- for (const mcp of config.mcp) {
190
- try {
191
- const loaded = await loadStdioMcpTools({ ...mcp, cwd });
192
- extra.push(...loaded.tools);
193
- closers.push(loaded.close);
194
- } catch {
195
- // fail-soft: missing extra MCP must not block the REPL
191
+ const reloadExtraMcp = async (): Promise<void> => {
192
+ const nextTools: McpToolDefinition[] = [];
193
+ const nextClosers: Array<() => void> = [];
194
+ for (const mcp of config.mcp) {
195
+ try {
196
+ const loaded = await loadStdioMcpTools({ ...mcp, cwd });
197
+ nextTools.push(...loaded.tools);
198
+ nextClosers.push(loaded.close);
199
+ } catch {
200
+ // fail-soft: missing extra MCP must not block the REPL
201
+ }
202
+ }
203
+ for (const server of listUserMcpServers(cwd)) {
204
+ try {
205
+ if (server.kind === "stdio" && server.command) {
206
+ const loaded = await loadStdioMcpTools({
207
+ command: server.command,
208
+ args: server.args,
209
+ env: server.env,
210
+ cwd,
211
+ namePrefix: userMcpToolPrefix(server.id),
212
+ });
213
+ nextTools.push(...loaded.tools);
214
+ nextClosers.push(loaded.close);
215
+ } else if (server.kind === "http" && server.url) {
216
+ const tools = await buildRemoteMcpTools({
217
+ sources: [
218
+ {
219
+ connectorId: userMcpToolPrefix(server.id),
220
+ label: server.label,
221
+ mcpUrl: server.url,
222
+ accessToken: server.token ?? "",
223
+ },
224
+ ],
225
+ });
226
+ nextTools.push(...tools);
227
+ }
228
+ } catch {
229
+ // fail-soft: a bad user MCP must not block the REPL
230
+ }
196
231
  }
197
- }
232
+ for (const close of extraMcpClosers) close();
233
+ extraMcpClosers = nextClosers;
234
+ extraMcpTools = nextTools;
235
+ };
236
+ await reloadIntegrations();
237
+ await reloadExtraMcp();
198
238
 
199
239
  const or = resolveOpenRouter(config);
200
240
  let apiKey = or.apiKey;
@@ -228,6 +268,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
228
268
  ...createGitTools(cwd),
229
269
  createTodoTool(todos),
230
270
  ...extra,
271
+ ...extraMcpTools,
231
272
  ...integrationTools,
232
273
  createReadSkillTool(skills),
233
274
  ]);
@@ -316,6 +357,9 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
316
357
  async reloadIntegrations() {
317
358
  await reloadIntegrations();
318
359
  },
360
+ async reloadExtraMcp() {
361
+ await reloadExtraMcp();
362
+ },
319
363
  integrationIds() {
320
364
  return linkedMcpSources().map((source) => source.connectorId);
321
365
  },
@@ -488,7 +532,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
488
532
  return session;
489
533
  },
490
534
  close() {
491
- for (const close of closers) close();
535
+ for (const close of extraMcpClosers) close();
492
536
  void observability.flush();
493
537
  },
494
538
  };