@uniqbit/mate-core 1.0.0-canary.8 → 1.0.0-canary.9

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 (113) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/cli/commands/doctor.ts +17 -0
  4. package/src/cli/commands/vscode/release-vsix.json +2 -2
  5. package/src/create-mate.ts +4 -1
  6. package/src/lib/mcp-manager/resolve.ts +70 -0
  7. package/src/lib/mcp-manager/store.ts +109 -0
  8. package/src/lib/mcp-manager/types.ts +58 -0
  9. package/src/lib/mcp-manager/validate.ts +246 -0
  10. package/src/lib/orchestrator/config-store.ts +30 -7
  11. package/src/lib/orchestrator/engine-floor.ts +16 -4
  12. package/src/lib/orchestrator/engine-guard.ts +7 -1
  13. package/src/lib/orchestrator/types.ts +4 -0
  14. package/src/runtime/workflow/turn.ts +14 -12
  15. package/src/studio.ts +17 -0
  16. package/src/tools/setup/capabilities/mcp-manager.ts +74 -0
  17. package/src/tools/setup/context-services.ts +35 -6
  18. package/src/tools/setup/dynamic-plugins/audiences.ts +3 -2
  19. package/src/tools/setup/engine.ts +55 -3
  20. package/src/tools/setup/plugin.ts +14 -0
  21. package/src/tools/setup/providers/claude-format.ts +39 -2
  22. package/src/tools/setup/providers/claude.ts +10 -0
  23. package/src/tools/setup/providers/opencode-format.ts +13 -3
  24. package/studio-dist/client/assets/{button-amJ3g5oD.js → button-C9SQW3kI.js} +1 -1
  25. package/studio-dist/client/assets/{cn-BQPKiwI4.js → cn-DC80MJV0.js} +1 -1
  26. package/studio-dist/client/assets/{combobox-CJ7aGFid.js → combobox-D7mKYCBb.js} +1 -1
  27. package/studio-dist/client/assets/{companion-view-C_N237bf.js → companion-view-C1F0_jbt.js} +1 -1
  28. package/studio-dist/client/assets/{fields-BAiGkJ5N.js → fields-CEep8IFT.js} +1 -1
  29. package/studio-dist/client/assets/{friction-DqOU59v7.js → friction-D9dBU7WN.js} +1 -1
  30. package/studio-dist/client/assets/getting-started-BDyGvHhc.js +1 -0
  31. package/studio-dist/client/assets/{getting-started-djaQeWlu.js → getting-started-BN4aTpsz.js} +1 -1
  32. package/studio-dist/client/assets/getting-started._topic-B9ajbF4o.js +1 -0
  33. package/studio-dist/client/assets/getting-started.index-CYiBPtb7.js +1 -0
  34. package/studio-dist/client/assets/{graph-BYaD_5Bq.js → graph-ah7ZXfTa.js} +2 -2
  35. package/studio-dist/client/assets/{graph-canvas-ySGKMhmk.js → graph-canvas-Be5qgdDt.js} +1 -1
  36. package/studio-dist/client/assets/guides-CsL0660B.js +1 -0
  37. package/studio-dist/client/assets/{index-Qx7reRPD.js → index-zmRH87D4.js} +3 -3
  38. package/studio-dist/client/assets/{markdown-view-jMiaBTSO.js → markdown-view-dku7MGPn.js} +1 -1
  39. package/studio-dist/client/assets/{panel-C4bf_h2W.js → panel-COgk0vP5.js} +1 -1
  40. package/studio-dist/client/assets/{plugins._service._view-y6f2FDAB.js → plugins._service._view-Cn3WBHab.js} +1 -1
  41. package/studio-dist/client/assets/{prepaint-CKsXyJOR.js → prepaint-BkoDSw5X.js} +1 -1
  42. package/studio-dist/client/assets/{queries-Dfp5deWj.js → queries-CMvC2OkU.js} +1 -1
  43. package/studio-dist/client/assets/{reports-JFSwSueq.js → reports-C_AqLBYH.js} +1 -1
  44. package/studio-dist/client/assets/{routes-BdOWSgzK.js → routes-BokQmHtC.js} +1 -1
  45. package/studio-dist/client/assets/{search-CXosfvYh.js → search-DxidNK2M.js} +1 -1
  46. package/studio-dist/client/assets/{select-BHYYWPhK.js → select-CYFCbHUd.js} +1 -1
  47. package/studio-dist/client/assets/{skills-Bo9FLsBd.js → skills-R3vttWHM.js} +1 -1
  48. package/studio-dist/client/assets/{specs-BrCOjOch.js → specs-Bqd1ajyD.js} +1 -1
  49. package/studio-dist/client/assets/{specs-view-CdE2rlli.js → specs-view-znqFPx9p.js} +1 -1
  50. package/studio-dist/client/assets/{steps-CKUno4lh.js → steps-tVDWn7j6.js} +1 -1
  51. package/studio-dist/client/assets/{store-C3vJq8Wj.js → store-BYnEU33C.js} +1 -1
  52. package/studio-dist/client/assets/studio-ndtFcS2Y.js +100 -0
  53. package/studio-dist/client/assets/{studio-queries-BflKt9va.js → studio-queries-CkUSByy7.js} +1 -1
  54. package/studio-dist/client/assets/{usage-BLsLy0nN.js → usage-Kuhr8dSl.js} +1 -1
  55. package/studio-dist/client/assets/{useAnchoredPopupScrollLock-DC7f8GOp.js → useAnchoredPopupScrollLock-dc_kP4Go.js} +1 -1
  56. package/studio-dist/client/assets/{useMutation-uJUrejsi.js → useMutation-CqtM9COw.js} +1 -1
  57. package/studio-dist/client/assets/{vault-BB1B_OhR.js → vault-CSP8kwRg.js} +1 -1
  58. package/studio-dist/client/assets/{warnings-CqOOGlPD.js → warnings-Cnw99ugO.js} +1 -1
  59. package/studio-dist/client/assets/{workflow-BFzmI-06.js → workflow-BPJAmmZi.js} +1 -1
  60. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-gVfW5vIV.js → __23tanstack-start-server-fn-resolver-CS3QRY4Q.js} +18 -18
  61. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +58 -58
  62. package/studio-dist/server/assets/{button-D6bvrFmm.js → button-Ct_WeYLc.js} +1 -1
  63. package/studio-dist/server/assets/{cn-FXJAM0KO.js → cn-DWFJaP_9.js} +1 -1
  64. package/studio-dist/server/assets/{combobox-D2MbYV1O.js → combobox-17vO5Uz8.js} +6 -6
  65. package/studio-dist/server/assets/{companion-view-Mf1ANbMb.js → companion-view-JkxnGLlp.js} +2 -2
  66. package/studio-dist/server/assets/{companions-Dr6IpNAb.js → companions-YNLsbnch.js} +1 -1
  67. package/studio-dist/server/assets/{fields-B4mAPETz.js → fields-VytPpqBq.js} +2 -2
  68. package/studio-dist/server/assets/{friction-9a5S1m7U.js → friction-B6osqFSm.js} +8 -8
  69. package/studio-dist/server/assets/{friction-CWOTjpCV.js → friction-BW86PCPM.js} +2 -2
  70. package/studio-dist/server/assets/{getting-started-RU6tYU2Q.js → getting-started-CFHSeX5h.js} +2 -2
  71. package/studio-dist/server/assets/{getting-started._topic-C02HGrC6.js → getting-started._topic-BK2eU6AS.js} +2 -2
  72. package/studio-dist/server/assets/{getting-started.index-EzLRosbb.js → getting-started.index-DZLuXnNO.js} +2 -2
  73. package/studio-dist/server/assets/{graph-CZ2H9Fzr.js → graph-BJVZBevL.js} +8 -8
  74. package/studio-dist/server/assets/{graph-B11ITte0.js → graph-DGZHV-Ek.js} +1 -1
  75. package/studio-dist/server/assets/{graph-canvas-rP5TT14Z.js → graph-canvas-lrNT6jbl.js} +2 -2
  76. package/studio-dist/server/assets/{guides-B8HdeK_C.js → guides-CEwLOZb9.js} +1 -1
  77. package/studio-dist/server/assets/{guides-BGftp4wf.js → guides-_G8Vucsk.js} +1 -1
  78. package/studio-dist/server/assets/{guides.server-DqFQAStf.js → guides.server-ZWFKX2XJ.js} +1 -1
  79. package/studio-dist/server/assets/{markdown-view-CArpV-CS.js → markdown-view-Bmjghg_Z.js} +1 -1
  80. package/studio-dist/server/assets/{panel-DR0iq46J.js → panel-DvRjyil3.js} +4 -4
  81. package/studio-dist/server/assets/{plugins._service._view-n7u2k5dF.js → plugins._service._view-B32LzraG.js} +4 -4
  82. package/studio-dist/server/assets/{prepaint-B28ClcPN.js → prepaint-BEHwKl51.js} +1 -1
  83. package/studio-dist/server/assets/{queries-D-yVP9i0.js → queries-D6Vq0AuZ.js} +1 -1
  84. package/studio-dist/server/assets/{reports-B9k98oE6.js → reports-DDaH5k0H.js} +1 -1
  85. package/studio-dist/server/assets/{reports-C2SmTgqh.js → reports-Dn92pLap.js} +7 -7
  86. package/studio-dist/server/assets/{router-CPt0TAk_.js → router-Bjf4S9tO.js} +25 -25
  87. package/studio-dist/server/assets/{routes-CwH8LEy2.js → routes-B4sNiE0X.js} +8 -8
  88. package/studio-dist/server/assets/{search-b-yQesv3.js → search-DKeJRvg8.js} +1 -1
  89. package/studio-dist/server/assets/{select-C3i6TTX-.js → select-CVHYL7oR.js} +5 -5
  90. package/studio-dist/server/assets/{shell-CagqZZMZ.js → shell-BxbYYaAk.js} +2 -2
  91. package/studio-dist/server/assets/{skills-C21Mg_8-.js → skills-B4-0qpqN.js} +8 -8
  92. package/studio-dist/server/assets/{skills-DGg0mWDM.js → skills-Bj8eOgzR.js} +1 -1
  93. package/studio-dist/server/assets/{specs-DetoMiaB.js → specs-rfMug6qW.js} +4 -4
  94. package/studio-dist/server/assets/{specs-view-CmbfLDwN.js → specs-view-qi1SE1Sl.js} +10 -10
  95. package/studio-dist/server/assets/{steps-D1tYAyWZ.js → steps-rger6HJc.js} +1 -1
  96. package/studio-dist/server/assets/{store-aC-I6f6o.js → store-Dg9T7oWs.js} +1 -1
  97. package/studio-dist/server/assets/{studio-qRvQjRpz.js → studio-D79JzDLc.js} +1347 -0
  98. package/studio-dist/server/assets/{studio-queries-Dqf-3nzj.js → studio-queries-CeFfmIuM.js} +3 -3
  99. package/studio-dist/server/assets/{usage-CS4CBK9D.js → usage-BJgYWRCX.js} +9 -9
  100. package/studio-dist/server/assets/{usage-Cwle9-xY.js → usage-Dw_UQFX-.js} +1 -1
  101. package/studio-dist/server/assets/{useAnchoredPopupScrollLock-BjMNgXv9.js → useAnchoredPopupScrollLock-ciS_sEq3.js} +2 -2
  102. package/studio-dist/server/assets/{useMutation-DpBIuWXt.js → useMutation-DnWK0PhO.js} +2 -2
  103. package/studio-dist/server/assets/{vault-CEBBRLMb.js → vault-BzarssiL.js} +1 -1
  104. package/studio-dist/server/assets/{vault-DVQidlId.js → vault-CvlrLd2H.js} +6 -6
  105. package/studio-dist/server/assets/{views-UgO0Qz_g.js → views-CAxwKHMK.js} +2 -2
  106. package/studio-dist/server/assets/{warnings-C7hgXpdk.js → warnings-BpVCugHm.js} +2 -2
  107. package/studio-dist/server/assets/{workflow-6dZZ1ofw.js → workflow-BdrzcCt8.js} +9 -9
  108. package/studio-dist/server/server.js +2 -2
  109. package/studio-dist/client/assets/getting-started-yp42dj5S.js +0 -1
  110. package/studio-dist/client/assets/getting-started._topic-C9zVXz_m.js +0 -1
  111. package/studio-dist/client/assets/getting-started.index-DWbDKICP.js +0 -1
  112. package/studio-dist/client/assets/guides-D6T6W_jV.js +0 -1
  113. package/studio-dist/client/assets/studio-0ueISxwP.js +0 -100
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.0-canary.8",
3
+ "version": "1.0.0-canary.9",
4
4
  "description": "@mate:<path> mentions: find and attach files from the mate companion repo in the @ menu.",
5
5
  "author": {
6
6
  "name": "Kevin Tornquist"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniqbit/mate-core",
3
- "version": "1.0.0-canary.8",
3
+ "version": "1.0.0-canary.9",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,6 +25,7 @@ import type { GlobalConfigStore } from "../../lib/orchestrator/global-config-sto
25
25
  import { pathIsDirectory } from "../../lib/fs-utils";
26
26
  import { resolveRootContext, type RootContext } from "../../lib/orchestrator/root-context";
27
27
  import type { CapabilityConfig, FrameworkConfig, HubMember } from "../../lib/orchestrator/types";
28
+ import { missingMcpVariables, type MissingMcpVariable } from "../../lib/mcp-manager/resolve";
28
29
  import { locateOpenSpec, type OpenSpecLocation } from "../../lib/openspec-cli";
29
30
  import { MATE_CLAUDE_PLUGIN_NAME, withoutMateWrapperDirs } from "../../lib/package-paths";
30
31
  import {
@@ -119,6 +120,8 @@ export interface DoctorReport {
119
120
  audiences?: { declared: string[]; active: string | null };
120
121
  /** Set when `MATE_AUDIENCE` names an audience the companion does not declare. */
121
122
  audienceError?: string;
123
+ /** Variables the active audience's `mcpManager` servers need but the environment does not set; names only. */
124
+ mcpMissingVariables?: MissingMcpVariable[];
122
125
  /** IDs of the capabilities the verified plugins provide. */
123
126
  pluginCapabilities?: string[];
124
127
  engineRequirement?: { range: string; ok: boolean; detail: string };
@@ -564,6 +567,11 @@ export async function collectDoctorReport(deps: DoctorDeps = {}): Promise<Doctor
564
567
  if (warnings.length > 0) report.openspecRuleWarnings = warnings;
565
568
  }
566
569
 
570
+ if (root.config && (kind === "working" || kind === "companion")) {
571
+ const missing = missingMcpVariables(root.config, readAudienceSelection(env), env);
572
+ if (missing.length > 0) report.mcpMissingVariables = missing;
573
+ }
574
+
567
575
  if (root.rootPath && (kind === "working" || kind === "companion")) {
568
576
  const warnings = collectCompanionInstructionWarnings(root.rootPath);
569
577
  if (warnings.length > 0) report.companionInstructionWarnings = warnings;
@@ -779,6 +787,15 @@ function renderHumanReport(report: DoctorReport): void {
779
787
  ]),
780
788
  );
781
789
  }
790
+ if (report.mcpMissingVariables) {
791
+ printSection(
792
+ "MCP Server Variables",
793
+ renderTable(
794
+ ["Server", "Missing variable"],
795
+ report.mcpMissingVariables.map((entry) => [entry.server, entry.variable]),
796
+ ),
797
+ );
798
+ }
782
799
  if (report.hub) printSection("Hub Members", renderHubMembers(report.hub.members));
783
800
  // Companions with no drift produce no section at all: required plugins are
784
801
  // silent when healthy.
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.0.0-canary.8",
3
- "sha512": "sha512-eOxXhwtswLDZvHJJYI86S91PNqhNhKaGbbDbL4/TH5j2pxuyyHyOtBaYZGrH/0Hy6eGLSfJE1VMlCDJFfDcPjw=="
2
+ "version": "1.0.0-canary.9",
3
+ "sha512": "sha512-edfJ2SPotUD1hVW5lyvHcfrKColGjbOt3Cxwvx+S7s2bFLuCM9QUifSabD5PUBYr5siWStkT5kozpjt3lGfPxA=="
4
4
  }
@@ -3,6 +3,7 @@ import { setActiveDistribution, type DistributionConfig } from "./distribution";
3
3
  import { FRAMEWORK_NAME } from "./framework";
4
4
  import { currentSession } from "./lib/session-attribution";
5
5
  import { runRecordingFailure } from "./runtime/command-friction";
6
+ import { createMcpManagerPlugin } from "./tools/setup/capabilities/mcp-manager";
6
7
  import { createBunPlugin } from "./tools/setup/package-managers/bun";
7
8
  import { createUvPlugin } from "./tools/setup/package-managers/uv";
8
9
  import type { PluginRegistration } from "./tools/setup/plugin";
@@ -26,7 +27,8 @@ export interface MateCli {
26
27
  * Assemble a distribution from an identity config and plugin registration
27
28
  * entries. Distributions choose their plugin set; the framework always adds
28
29
  * bun as the required runtime substrate, uv for the capabilities that install
29
- * through it (enabled only by them, e.g. Graphify), plus gitignore management
30
+ * through it (enabled only by them, e.g. Graphify), the `mcp-manager`
31
+ * Capability (enabled by a `mcpManager` section), plus gitignore management
30
32
  * named after the framework identity (built last since it reads the full
31
33
  * plugin set). Returns the runnable CLI.
32
34
  */
@@ -35,6 +37,7 @@ export function createMate({ config, plugins, main: runMain = main }: CreateMate
35
37
  ...plugins,
36
38
  { plugin: createBunPlugin(), policy: "required" },
37
39
  { plugin: createUvPlugin(), policy: "optional" },
40
+ createMcpManagerPlugin(),
38
41
  createGitignorePlugin(FRAMEWORK_NAME),
39
42
  ]);
40
43
  setActiveDistribution({ config, registry });
@@ -0,0 +1,70 @@
1
+ import { audienceEntry, normalizeBaseAudience } from "../../tools/setup/dynamic-plugins/audiences";
2
+ import type {
3
+ McpManagerAudienceSelection,
4
+ McpManagerConfig,
5
+ McpManagerSelection,
6
+ ResolvedMcpServer,
7
+ } from "./types";
8
+ import { isRecord, parseHeaderRef } from "./validate";
9
+
10
+ function members(section: McpManagerConfig, groups: string[] | undefined): string[] {
11
+ return (groups ?? []).flatMap((group) => section.groups?.[group] ?? []);
12
+ }
13
+
14
+ function audienceSelection(raw: unknown, audience: string | null): McpManagerAudienceSelection {
15
+ const entry = audienceEntry(raw, audience);
16
+ return isRecord(entry) && isRecord(entry.mcpManager)
17
+ ? (entry.mcpManager as McpManagerAudienceSelection)
18
+ : {};
19
+ }
20
+
21
+ /** A variable an effective server needs that the environment leaves unset or empty. */
22
+ export interface MissingMcpVariable {
23
+ server: string;
24
+ variable: string;
25
+ }
26
+
27
+ /** Variables a server reads: its `env` names and the one each header references. */
28
+ function serverVariables(server: ResolvedMcpServer["server"]): string[] {
29
+ const headers = "headers" in server ? Object.values(server.headers ?? {}) : [];
30
+ const fromHeaders = headers.flatMap((value) => parseHeaderRef(value)?.variable ?? []);
31
+ return [...new Set([...(server.env ?? []), ...fromHeaders])];
32
+ }
33
+
34
+ /** Checks presence only; a value never leaves `env`. */
35
+ export function missingMcpVariables(
36
+ raw: unknown,
37
+ audience: string | null,
38
+ env: Record<string, string | undefined>,
39
+ ): MissingMcpVariable[] {
40
+ return resolveMcpServers(raw, audience).flatMap(({ name, server }) =>
41
+ serverVariables(server)
42
+ .filter((variable) => !env[variable])
43
+ .map((variable) => ({ server: name, variable })),
44
+ );
45
+ }
46
+
47
+ /**
48
+ * The effective servers of an already validated `framework.yaml` for
49
+ * `audience`, ordered by name. Group decisions apply before server decisions,
50
+ * so a named server beats a group; `null`, `base` or an undeclared audience
51
+ * gives the base set.
52
+ */
53
+ export function resolveMcpServers(raw: unknown, audience: string | null): ResolvedMcpServer[] {
54
+ const normalized = normalizeBaseAudience(raw);
55
+ if (!isRecord(normalized) || !isRecord(normalized.mcpManager)) return [];
56
+ const section = normalized.mcpManager as McpManagerConfig;
57
+ const base: McpManagerSelection = section.enabled ?? {};
58
+ const { enable = {}, disable = {} } = audienceSelection(normalized, audience);
59
+
60
+ const names = new Set([...(base.servers ?? []), ...members(section, base.groups)]);
61
+ for (const name of members(section, enable.groups)) names.add(name);
62
+ for (const name of members(section, disable.groups)) names.delete(name);
63
+ for (const name of enable.servers ?? []) names.add(name);
64
+ for (const name of disable.servers ?? []) names.delete(name);
65
+
66
+ return [...names]
67
+ .filter((name) => section.servers?.[name] !== undefined)
68
+ .toSorted()
69
+ .map((name) => ({ name, server: section.servers![name] }));
70
+ }
@@ -0,0 +1,109 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+
4
+ import { parseDocument } from "yaml";
5
+
6
+ import { FRAMEWORK_NAME } from "../../framework";
7
+ import { companionFrameworkConfigPath } from "../../runtime/policy";
8
+ import { writeAtomic } from "../../runtime/write-atomic";
9
+ import { BASE_AUDIENCE, declaredAudiences } from "../../tools/setup/dynamic-plugins/audiences";
10
+ import { parseFrameworkConfig } from "../orchestrator/config-store";
11
+ import { ConfigError, type FrameworkConfig } from "../orchestrator/types";
12
+ import { resolveMcpServers } from "./resolve";
13
+ import type { McpManagerAudienceSelection, McpManagerConfig } from "./types";
14
+ import { mcpManagerEngineRange } from "./validate";
15
+
16
+ /** `framework.yaml` changed after the read whose token a write carries. */
17
+ export class McpManagerConflictError extends Error {
18
+ constructor() {
19
+ super("framework.yaml changed since it was read; read it again and reapply the change.");
20
+ }
21
+ }
22
+
23
+ export interface McpManagerSnapshot {
24
+ /** The root section; null when the companion declares none. */
25
+ catalog: McpManagerConfig | null;
26
+ /** Each declared audience's selection; `{}` when it selects nothing. */
27
+ audiences: Record<string, McpManagerAudienceSelection>;
28
+ /** Effective server names for the base set and per declared audience. */
29
+ effective: { base: string[]; audiences: Record<string, string[]> };
30
+ /** Content hash of `framework.yaml`, the concurrency token a write carries. */
31
+ token: string;
32
+ }
33
+
34
+ /**
35
+ * A change to the section. `catalog: null` removes the root section; an
36
+ * audience mapped to null loses its selection. Absent keys stay unchanged.
37
+ */
38
+ export interface McpManagerPatch {
39
+ catalog?: McpManagerConfig | null;
40
+ audiences?: Record<string, McpManagerAudienceSelection | null>;
41
+ }
42
+
43
+ function tokenOf(text: string): string {
44
+ return crypto.createHash("sha256").update(text).digest("hex");
45
+ }
46
+
47
+ function snapshotOf(config: FrameworkConfig, token: string): McpManagerSnapshot {
48
+ const names = declaredAudiences(config);
49
+ const effective = (audience: string | null) =>
50
+ resolveMcpServers(config, audience).map((server) => server.name);
51
+ return {
52
+ catalog: config.mcpManager ?? null,
53
+ audiences: Object.fromEntries(
54
+ names.map((name) => [name, config.audiences?.[name]?.mcpManager ?? {}]),
55
+ ),
56
+ effective: {
57
+ base: effective(null),
58
+ audiences: Object.fromEntries(names.map((name) => [name, effective(name)])),
59
+ },
60
+ token,
61
+ };
62
+ }
63
+
64
+ async function readText(companionPath: string): Promise<string> {
65
+ return fs.readFile(companionFrameworkConfigPath(companionPath), "utf8");
66
+ }
67
+
68
+ /** The catalog, audience selections and effective sets, validated as loading validates them. */
69
+ export async function readMcpManager(companionPath: string): Promise<McpManagerSnapshot> {
70
+ const text = await readText(companionPath);
71
+ return snapshotOf(parseFrameworkConfig(parseDocument(text).toJS()), tokenOf(text));
72
+ }
73
+
74
+ /**
75
+ * Applies `patch` to `framework.yaml`, keeping comments, key order and every
76
+ * other key. Fails with {@link McpManagerConflictError} when the file changed
77
+ * since `token`'s read, and with the loader's error when the result is
78
+ * invalid; either way the file is left unchanged.
79
+ */
80
+ export async function writeMcpManager(
81
+ companionPath: string,
82
+ patch: McpManagerPatch,
83
+ token: string,
84
+ ): Promise<McpManagerSnapshot> {
85
+ const text = await readText(companionPath);
86
+ if (tokenOf(text) !== token) throw new McpManagerConflictError();
87
+
88
+ const document = parseDocument(text);
89
+ if (patch.catalog === null) document.delete("mcpManager");
90
+ else if (patch.catalog !== undefined) document.set("mcpManager", patch.catalog);
91
+ for (const [audience, selection] of Object.entries(patch.audiences ?? {})) {
92
+ if (audience === BASE_AUDIENCE) {
93
+ throw new ConfigError(
94
+ `"${BASE_AUDIENCE}" is the base set; write its servers to the catalog.`,
95
+ );
96
+ }
97
+ if (selection === null) document.deleteIn(["audiences", audience, "mcpManager"]);
98
+ else document.setIn(["audiences", audience, "mcpManager"], selection);
99
+ }
100
+
101
+ const raw = document.toJS() as Record<string, unknown>;
102
+ const config = parseFrameworkConfig(raw);
103
+ const raised = mcpManagerEngineRange(raw);
104
+ if (raised !== null) document.setIn(["engines", FRAMEWORK_NAME], raised);
105
+
106
+ const next = document.toString();
107
+ await writeAtomic(companionFrameworkConfigPath(companionPath), next);
108
+ return snapshotOf(config, tokenOf(next));
109
+ }
@@ -0,0 +1,58 @@
1
+ /** Remote transports a declared server may name; absent means `http`. */
2
+ export const MCP_MANAGER_TRANSPORTS = ["http", "sse"] as const;
3
+ export type McpManagerTransport = (typeof MCP_MANAGER_TRANSPORTS)[number];
4
+
5
+ /** Fields every declared server shares. Holds variable names, never values. */
6
+ interface McpManagerServerBase {
7
+ /** Environment variable names the server reads, rendered as runtime references. */
8
+ env?: string[];
9
+ }
10
+
11
+ /** A server Mate starts as a local process. */
12
+ export interface McpManagerStdioServer extends McpManagerServerBase {
13
+ command: string;
14
+ args?: string[];
15
+ }
16
+
17
+ /** A server Mate reaches over the network. */
18
+ export interface McpManagerRemoteServer extends McpManagerServerBase {
19
+ url: string;
20
+ transport?: McpManagerTransport;
21
+ /** Header name to `<scheme prefix>${NAME}`, e.g. `Bearer ${ACME_KEY}`. */
22
+ headers?: Record<string, string>;
23
+ }
24
+
25
+ export type McpManagerServer = McpManagerStdioServer | McpManagerRemoteServer;
26
+
27
+ /** Server and group names, as a selection lists them. */
28
+ export interface McpManagerSelection {
29
+ servers?: string[];
30
+ groups?: string[];
31
+ }
32
+
33
+ /** The `mcpManager` section at the root of `framework.yaml`. */
34
+ export interface McpManagerConfig {
35
+ servers?: Record<string, McpManagerServer>;
36
+ /** Group name to member server names. */
37
+ groups?: Record<string, string[]>;
38
+ /** The base selection. */
39
+ enabled?: McpManagerSelection;
40
+ }
41
+
42
+ /** `audiences.<name>.mcpManager`: selects from the root catalog only. */
43
+ export interface McpManagerAudienceSelection {
44
+ enable?: McpManagerSelection;
45
+ disable?: McpManagerSelection;
46
+ }
47
+
48
+ /** A header value split into its literal prefix and the one variable it references. */
49
+ export interface McpManagerHeaderRef {
50
+ prefix: string;
51
+ variable: string;
52
+ }
53
+
54
+ /** One server of an effective set, ready to become an MCP descriptor. */
55
+ export interface ResolvedMcpServer {
56
+ name: string;
57
+ server: McpManagerServer;
58
+ }
@@ -0,0 +1,246 @@
1
+ import { raisedEngineRange } from "../orchestrator/engine-floor";
2
+ import { ConfigError } from "../orchestrator/types";
3
+ import { MCP_MANAGER_TRANSPORTS, type McpManagerConfig, type McpManagerHeaderRef } from "./types";
4
+
5
+ /** First Mate release that reads `mcpManager`; the `engines.mate` floor a save sets. */
6
+ export const MCP_MANAGER_VERSION = "1.0.0-canary.9";
7
+
8
+ export const MCP_MANAGER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
9
+ export const MCP_MANAGER_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
10
+ export const MCP_MANAGER_HEADER_PREFIXES = ["Bearer ", "Basic ", "Token "] as const;
11
+
12
+ const HEADER_NAME_PATTERN = /^[A-Za-z0-9-]+$/;
13
+ const HEADER_VALUE_PATTERN = /^(Bearer |Basic |Token )?\$\{([A-Z_][A-Z0-9_]*)\}$/;
14
+
15
+ const SECTION_KEYS = ["servers", "groups", "enabled"] as const;
16
+ const STDIO_KEYS = ["command", "args", "env"] as const;
17
+ const REMOTE_KEYS = ["url", "transport", "headers", "env"] as const;
18
+ const SELECTION_KEYS = ["servers", "groups"] as const;
19
+ const AUDIENCE_KEYS = ["enable", "disable"] as const;
20
+
21
+ export function isRecord(value: unknown): value is Record<string, unknown> {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ function fail(message: string): never {
26
+ throw new ConfigError(message);
27
+ }
28
+
29
+ function checkKeys(where: string, value: Record<string, unknown>, allowed: readonly string[]) {
30
+ for (const key of Object.keys(value)) {
31
+ if (!allowed.includes(key)) {
32
+ fail(`${where}: unknown key "${key}" (allowed: ${allowed.join(", ")}).`);
33
+ }
34
+ }
35
+ }
36
+
37
+ /** `${NAME}` with an optional known scheme prefix, or null for anything else. */
38
+ export function parseHeaderRef(value: unknown): McpManagerHeaderRef | null {
39
+ if (typeof value !== "string") return null;
40
+ const match = HEADER_VALUE_PATTERN.exec(value);
41
+ return match ? { prefix: match[1] ?? "", variable: match[2] } : null;
42
+ }
43
+
44
+ function validateEnv(where: string, env: unknown): void {
45
+ if (!Array.isArray(env)) {
46
+ fail(
47
+ `${where}: env lists variable names only, e.g. env: [ACME_TOKEN]; it is not a mapping of values.`,
48
+ );
49
+ }
50
+ env.forEach((entry, index) => {
51
+ if (typeof entry !== "string" || !MCP_MANAGER_VARIABLE_PATTERN.test(entry)) {
52
+ fail(
53
+ `${where}: env entry ${index + 1} is not a variable name (must match ${MCP_MANAGER_VARIABLE_PATTERN.source}); env lists names only, never values.`,
54
+ );
55
+ }
56
+ });
57
+ }
58
+
59
+ function validateHeaders(where: string, headers: unknown): void {
60
+ if (!isRecord(headers)) fail(`${where}: headers must be a mapping of header name to reference.`);
61
+ for (const [header, value] of Object.entries(headers)) {
62
+ if (!HEADER_NAME_PATTERN.test(header))
63
+ fail(`${where}: header "${header}" is not a header name.`);
64
+ if (parseHeaderRef(value) === null) {
65
+ fail(
66
+ `${where}: header "${header}" must be an optional scheme prefix (${MCP_MANAGER_HEADER_PREFIXES.map((prefix) => prefix.trim()).join(", ")}) followed by exactly one \${NAME} reference; literal values are not allowed.`,
67
+ );
68
+ }
69
+ }
70
+ }
71
+
72
+ /** An absent list is empty. */
73
+ function validateStringList(where: string, value: unknown): string[] {
74
+ if (value === undefined) return [];
75
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) {
76
+ fail(`${where} must be a list of names.`);
77
+ }
78
+ return value;
79
+ }
80
+
81
+ function validateServer(name: string, server: unknown): void {
82
+ const where = `mcpManager.servers.${name}`;
83
+ if (!MCP_MANAGER_NAME_PATTERN.test(name)) {
84
+ fail(`Invalid MCP server name "${name}": must match ${MCP_MANAGER_NAME_PATTERN.source}.`);
85
+ }
86
+ if (!isRecord(server)) fail(`${where} must be a mapping.`);
87
+ const hasCommand = Object.hasOwn(server, "command");
88
+ const hasUrl = Object.hasOwn(server, "url");
89
+ if (hasCommand && hasUrl) {
90
+ fail(`${where} declares both "command" and "url"; a server has exactly one transport.`);
91
+ }
92
+ if (!hasCommand && !hasUrl) fail(`${where} needs either "command" or "url".`);
93
+
94
+ if (hasCommand) {
95
+ checkKeys(where, server, STDIO_KEYS);
96
+ if (typeof server.command !== "string" || server.command.trim() === "") {
97
+ fail(`${where}: command must be a non-empty string.`);
98
+ }
99
+ validateStringList(`${where}.args`, server.args);
100
+ } else {
101
+ checkKeys(where, server, REMOTE_KEYS);
102
+ if (typeof server.url !== "string" || !/^https?:\/\/\S+$/.test(server.url)) {
103
+ fail(`${where}: url must be an http or https URL.`);
104
+ }
105
+ if (
106
+ server.transport !== undefined &&
107
+ !MCP_MANAGER_TRANSPORTS.includes(server.transport as never)
108
+ ) {
109
+ fail(`${where}: transport must be one of ${MCP_MANAGER_TRANSPORTS.join(", ")}.`);
110
+ }
111
+ if (server.headers !== undefined) validateHeaders(where, server.headers);
112
+ }
113
+ if (server.env !== undefined) validateEnv(where, server.env);
114
+ }
115
+
116
+ /** Server and group names a valid root section declares. */
117
+ interface Catalog {
118
+ servers: ReadonlySet<string>;
119
+ groups: ReadonlySet<string>;
120
+ }
121
+
122
+ /** An absent selection names nothing. */
123
+ function validateSelection(
124
+ where: string,
125
+ selection: unknown,
126
+ catalog: Catalog,
127
+ ): { servers: string[]; groups: string[] } {
128
+ if (selection === undefined) return { servers: [], groups: [] };
129
+ if (!isRecord(selection)) fail(`${where} must be a mapping with servers and groups lists.`);
130
+ checkKeys(where, selection, SELECTION_KEYS);
131
+ const named = {
132
+ servers: validateStringList(`${where}.servers`, selection.servers),
133
+ groups: validateStringList(`${where}.groups`, selection.groups),
134
+ };
135
+ for (const server of named.servers) {
136
+ if (!catalog.servers.has(server)) fail(`${where}: unknown MCP server "${server}".`);
137
+ }
138
+ for (const group of named.groups) {
139
+ if (!catalog.groups.has(group)) fail(`${where}: unknown MCP server group "${group}".`);
140
+ }
141
+ return named;
142
+ }
143
+
144
+ function catalogOf(section: unknown): Catalog {
145
+ return {
146
+ servers: new Set(
147
+ isRecord(section) && isRecord(section.servers) ? Object.keys(section.servers) : [],
148
+ ),
149
+ groups: new Set(
150
+ isRecord(section) && isRecord(section.groups) ? Object.keys(section.groups) : [],
151
+ ),
152
+ };
153
+ }
154
+
155
+ /** Validates the root `mcpManager` section; error texts never repeat a configured value. */
156
+ export function validateMcpManagerSection(section: unknown): asserts section is McpManagerConfig {
157
+ if (!isRecord(section)) fail("mcpManager must be a mapping with servers, groups and enabled.");
158
+ checkKeys("mcpManager", section, SECTION_KEYS);
159
+
160
+ if (section.servers !== undefined) {
161
+ if (!isRecord(section.servers)) fail("mcpManager.servers must be a mapping of name to server.");
162
+ for (const [name, server] of Object.entries(section.servers)) validateServer(name, server);
163
+ }
164
+ const catalog = catalogOf(section);
165
+
166
+ if (section.groups !== undefined) {
167
+ if (!isRecord(section.groups)) fail("mcpManager.groups must be a mapping of name to servers.");
168
+ for (const [name, members] of Object.entries(section.groups)) {
169
+ if (!MCP_MANAGER_NAME_PATTERN.test(name)) {
170
+ fail(
171
+ `Invalid MCP server group name "${name}": must match ${MCP_MANAGER_NAME_PATTERN.source}.`,
172
+ );
173
+ }
174
+ if (catalog.servers.has(name)) {
175
+ fail(
176
+ `mcpManager: "${name}" names both a server and a group; servers and groups share one namespace.`,
177
+ );
178
+ }
179
+ for (const member of validateStringList(`mcpManager.groups.${name}`, members)) {
180
+ if (!catalog.servers.has(member)) {
181
+ fail(`mcpManager.groups.${name}: unknown MCP server "${member}".`);
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ validateSelection("mcpManager.enabled", section.enabled, catalog);
188
+ }
189
+
190
+ /**
191
+ * Validates `audiences.<audience>.mcpManager` against the root catalog
192
+ * (`undefined` when the companion declares none).
193
+ */
194
+ export function validateAudienceMcpManager(
195
+ audience: string,
196
+ selection: unknown,
197
+ root: unknown,
198
+ ): void {
199
+ const where = `audience "${audience}": mcpManager`;
200
+ if (!isRecord(selection)) fail(`${where} must be a mapping with enable and disable.`);
201
+ checkKeys(where, selection, AUDIENCE_KEYS);
202
+ const catalog = catalogOf(root);
203
+ const enable = validateSelection(`${where}.enable`, selection.enable, catalog);
204
+ const disable = validateSelection(`${where}.disable`, selection.disable, catalog);
205
+ for (const kind of ["servers", "groups"] as const) {
206
+ const disabled = new Set(disable[kind]);
207
+ const both = enable[kind].find((name) => disabled.has(name));
208
+ if (both !== undefined) {
209
+ fail(`${where}: "${both}" is both enabled and disabled under ${kind}; keep one.`);
210
+ }
211
+ }
212
+ }
213
+
214
+ /** True when `mcpManager` appears at the root or under any audience. */
215
+ export function declaresMcpManager(config: { mcpManager?: unknown; audiences?: unknown }): boolean {
216
+ if (config.mcpManager !== undefined) return true;
217
+ return (
218
+ isRecord(config.audiences) &&
219
+ Object.values(config.audiences).some(
220
+ (audience) => isRecord(audience) && audience.mcpManager !== undefined,
221
+ )
222
+ );
223
+ }
224
+
225
+ /** The `engines.mate` range a save must write when the config declares `mcpManager`, else null. */
226
+ export function mcpManagerEngineRange(config: {
227
+ mcpManager?: unknown;
228
+ audiences?: unknown;
229
+ engines?: unknown;
230
+ }): string | null {
231
+ return declaresMcpManager(config) ? raisedEngineRange(config.engines, MCP_MANAGER_VERSION) : null;
232
+ }
233
+
234
+ /** The root section and every audience selection of a parsed `framework.yaml`. */
235
+ export function validateMcpManagerConfig(config: {
236
+ mcpManager?: unknown;
237
+ audiences?: unknown;
238
+ }): void {
239
+ if (config.mcpManager !== undefined) validateMcpManagerSection(config.mcpManager);
240
+ if (!isRecord(config.audiences)) return;
241
+ for (const [name, audience] of Object.entries(config.audiences)) {
242
+ if (isRecord(audience) && audience.mcpManager !== undefined) {
243
+ validateAudienceMcpManager(name, audience.mcpManager, config.mcpManager);
244
+ }
245
+ }
246
+ }
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { normalizeBaseAudience } from "../../tools/setup/dynamic-plugins/audiences";
4
4
 
5
5
  import { FRAMEWORK_NAME } from "../../framework";
6
+ import { mcpManagerEngineRange, validateMcpManagerConfig } from "../mcp-manager/validate";
6
7
  import { declaredAllowedAgents } from "../../runtime/policy";
7
8
  import {
8
9
  getDefaultSetupSelections,
@@ -149,7 +150,7 @@ function validatePluginDeclarations(config: FrameworkConfig): void {
149
150
 
150
151
  export const AUDIENCE_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
151
152
 
152
- const AUDIENCE_KEYS = ["capabilities", "plugins", "studio"] as const;
153
+ const AUDIENCE_KEYS = ["capabilities", "plugins", "studio", "mcpManager"] as const;
153
154
 
154
155
  function isRecord(value: unknown): value is Record<string, unknown> {
155
156
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -225,6 +226,14 @@ function validateAudienceCapabilities(
225
226
  }
226
227
  }
227
228
 
229
+ /** Only companions declare MCP servers; audiences select from the root catalog. */
230
+ function validateMcpManager(config: FrameworkConfig): void {
231
+ if (config.type === "hub" && config.mcpManager !== undefined) {
232
+ throw new ConfigError('Only companions may declare mcpManager; a "hub" framework may not.');
233
+ }
234
+ validateMcpManagerConfig(config);
235
+ }
236
+
228
237
  /**
229
238
  * Validates the optional `audiences` mapping. Only companions may declare
230
239
  * audiences; names are safe identifiers and keys form a closed set so typos
@@ -294,6 +303,18 @@ function validateAudiences(config: FrameworkConfig): void {
294
303
  }
295
304
  }
296
305
 
306
+ /** Parsed `framework.yaml` as loading sees it: normalized, migrated, defaulted and validated. */
307
+ export function parseFrameworkConfig(raw: unknown): FrameworkConfig {
308
+ const merged = mergeWithDefaults(
309
+ migrateProfilesToAllowedAgents(normalizeBaseAudience(raw as FrameworkConfig)),
310
+ );
311
+ validateHubConfig(merged);
312
+ validatePluginDeclarations(merged);
313
+ validateAudiences(merged);
314
+ validateMcpManager(merged);
315
+ return merged;
316
+ }
317
+
297
318
  export class ConfigStore extends YamlFileStore<FrameworkConfig> {
298
319
  constructor(configPath = process.env.MATE_CONFIG ?? defaultConfigPath()) {
299
320
  super(path.resolve(configPath));
@@ -301,13 +322,15 @@ export class ConfigStore extends YamlFileStore<FrameworkConfig> {
301
322
 
302
323
  /** Either file shape loads as the base set at the root; the next save writes the root shape. */
303
324
  override async load(): Promise<FrameworkConfig> {
304
- const merged = mergeWithDefaults(
305
- migrateProfilesToAllowedAgents(normalizeBaseAudience(await super.load())),
325
+ return parseFrameworkConfig(await super.load());
326
+ }
327
+
328
+ /** A save holding `mcpManager` raises `engines.mate`; canaries up to 1.0.0-canary.8 still pass it (pre-release fallback). */
329
+ override async save(data: FrameworkConfig): Promise<void> {
330
+ const raised = mcpManagerEngineRange(data);
331
+ await super.save(
332
+ raised === null ? data : { ...data, engines: { ...data.engines, [FRAMEWORK_NAME]: raised } },
306
333
  );
307
- validateHubConfig(merged);
308
- validatePluginDeclarations(merged);
309
- validateAudiences(merged);
310
- return merged;
311
334
  }
312
335
 
313
336
  protected async onMissing(): Promise<FrameworkConfig> {