You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by zh...@apache.org on 2026/09/03 17:00:55 UTC

(maka) 02/02: fix(desktop): chunk and degrade oversized MCP capability manifests

This is an automated email from the ASF dual-hosted git repository.

me2seeks pushed a commit to branch fix/desktop-mcp-capability-schema
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 78db038674a2ac502de51d309e1f0e0a4f5df228
Author: me2seeks <me...@gmail.com>
AuthorDate: Fri Sep 4 00:59:43 2026 +0800

    fix(desktop): chunk and degrade oversized MCP capability manifests
    
    A desktop_mcp group beyond the 64-tool single-offer limit failed the full
    manifest decode, taking Browser, Settings, and Rive registration down with
    it. Chunk dynamic groups into stable per-offer ids while keeping the group's
    server identity, shed trailing dynamic tools when the total tool, offer, or
    byte budgets are exceeded, keep fixed groups loud when they overflow, decode
    the manifest authoritatively before it is sent, and report omissions through
    a visible diagnostic (#4490).
---
 .../src/main/__tests__/mcp-runtime-e2e.test.ts     |   7 +-
 .../runtime-host-native-capabilities.test.ts       | 183 +++++++++++++++++++++
 .../src/main/runtime-host-desktop-candidate.ts     |   1 +
 .../src/main/runtime-host-native-capabilities.ts   | 148 +++++++++++++++--
 4 files changed, 328 insertions(+), 11 deletions(-)

diff --git a/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts b/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts
index 3896f35231..a87ea2ca71 100644
--- a/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts
+++ b/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts
@@ -103,6 +103,7 @@ test('MCP tools stay bound to the connection generation that advertised them', a
       ),
       /not offered/u,
     );
+    let admissionEvidence: unknown;
     assert.deepEqual(
       await provider.call(
         {
@@ -120,7 +121,9 @@ test('MCP tools stay bound to the connection generation that advertised them', a
         },
         {
           signal: new AbortController().signal,
-          accept: async () => undefined,
+          accept: async (evidence) => {
+            admissionEvidence = evidence;
+          },
         },
       ),
       {
@@ -130,6 +133,8 @@ test('MCP tools stay bound to the connection generation that advertised them', a
         ],
       },
     );
+    // The Host managed admission policy for desktop_mcp requires this contract.
+    assert.deepEqual(admissionEvidence, { kind: 'none' });
 
     const result = await echo.impl({ value: 'runtime-e2e' }, {
       sessionId: 'session', turnId: 'turn', cwd: process.cwd(), toolCallId: 'call',
diff --git a/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts b/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts
index 98d97e5ba9..bb63ec3dfc 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts
@@ -524,6 +524,189 @@ test('dispatches through the same immutable tool snapshot it advertised', async
   );
 });
 
+test('chunks a dynamic capability group beyond the single-offer tool limit', async () => {
+  const mcpTools = Array.from({ length: 65 }, (_, index) =>
+    tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => `tool-${index}`),
+  );
+  const provider = createDesktopNativeCapabilityProvider({
+    browserTools: [tool('browser_snapshot', z.object({}), async () => 'ok')],
+    resolveBrowserUrl: () => 'https://example.com/',
+    releaseBrowserSession() {},
+    computerUseTools: [] as never,
+    releaseComputerUseSession() {},
+    additionalGroups: () => [
+      {
+        offerId: 'desktop_mcp',
+        label: 'MCP',
+        description: 'MCP tools connected by this Desktop client.',
+        tools: mcpTools,
+        omitUnsupportedTools: true,
+      },
+    ],
+  });
+
+  assert.deepEqual(
+    provider.offers().map((offer) => [offer.offerId, offer.tools.length] as const),
+    [
+      ['desktop_browser', 1],
+      ['desktop_mcp', 64],
+      ['desktop_mcp_2', 1],
+    ],
+  );
+  // Chunked offers keep the group's server identity.
+  assert.equal(provider.offers()[2]?.tools[0]?.serverId, 'desktop_mcp');
+  assert.equal(provider.offers()[2]?.tools[0]?.name, 'mcp_tool_064');
+  assert.doesNotThrow(() =>
+    decodeClientCapabilityReplaceInput({
+      registrationId: 'registration-1',
+      offers: provider.offers(),
+    }),
+  );
+  // A tool in a later chunk dispatches through its chunk offerId.
+  assert.deepEqual(
+    await call(
+      provider,
+      capabilityFrame({
+        offerId: 'desktop_mcp_2',
+        serverId: 'desktop_mcp',
+        toolName: 'mcp_tool_064',
+        arguments: {},
+      }),
+    ),
+    { content: [{ type: 'text', text: 'tool-64' }] },
+  );
+  await provider.close();
+});
+
+test('omits trailing dynamic tools beyond the manifest tool budget and keeps fixed groups', async () => {
+  const diagnostics: string[] = [];
+  const mcpTools = Array.from({ length: 300 }, (_, index) =>
+    tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => 'ok'),
+  );
+  const provider = createDesktopNativeCapabilityProvider(
+    {
+      browserTools: [tool('browser_snapshot', z.object({}), async () => 'ok')],
+      resolveBrowserUrl: () => 'https://example.com/',
+      releaseBrowserSession() {},
+      computerUseTools: [] as never,
+      releaseComputerUseSession() {},
+      additionalGroups: () => [
+        {
+          offerId: 'desktop_mcp',
+          label: 'MCP',
+          description: 'MCP tools connected by this Desktop client.',
+          tools: mcpTools,
+          omitUnsupportedTools: true,
+        },
+      ],
+    },
+    { onDiagnostic: (diagnostic) => diagnostics.push(diagnostic) },
+  );
+
+  const offers = provider.offers();
+  assert.equal(offers[0]?.offerId, 'desktop_browser');
+  assert.equal(offers[0]?.tools.length, 1);
+  let toolCount = 0;
+  for (const offer of offers) toolCount += offer.tools.length;
+  assert.equal(toolCount, 256);
+  assert.equal(offers.at(-1)?.tools.at(-1)?.name, 'mcp_tool_254');
+  assert.doesNotThrow(() =>
+    decodeClientCapabilityReplaceInput({
+      registrationId: 'registration-1',
+      offers,
+    }),
+  );
+  assert.equal(diagnostics.length, 1);
+  assert.match(diagnostics[0] ?? '', /omitted 45 MCP tool/u);
+  assert.match(diagnostics[0] ?? '', /mcp_tool_255/u);
+  await provider.close();
+});
+
+test('omits trailing dynamic tools beyond the manifest byte budget', () => {
+  const diagnostics: string[] = [];
+  const mcpTools = Array.from({ length: 80 }, (_, index) => ({
+    ...tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => 'ok'),
+    description: `mcp_tool_${index} ${'x'.repeat(1_000)}`,
+  }));
+  const provider = createDesktopNativeCapabilityProvider(
+    {
+      browserTools: [],
+      resolveBrowserUrl: () => 'https://example.com/',
+      releaseBrowserSession() {},
+      computerUseTools: [] as never,
+      releaseComputerUseSession() {},
+      additionalGroups: () => [
+        {
+          offerId: 'desktop_mcp',
+          label: 'MCP',
+          description: 'MCP tools connected by this Desktop client.',
+          tools: mcpTools,
+          omitUnsupportedTools: true,
+        },
+      ],
+    },
+    { onDiagnostic: (diagnostic) => diagnostics.push(diagnostic) },
+  );
+
+  const offers = provider.offers();
+  const kept = offers.flatMap((offer) => offer.tools.map((descriptor) => descriptor.name));
+  assert.ok(kept.length > 0 && kept.length < 80);
+  assert.deepEqual(
+    kept,
+    mcpTools.slice(0, kept.length).map((candidate) => candidate.name),
+  );
+  assert.doesNotThrow(() =>
+    decodeClientCapabilityReplaceInput({
+      registrationId: 'registration-1',
+      offers,
+    }),
+  );
+  assert.equal(diagnostics.length, 1);
+  assert.match(diagnostics[0] ?? '', /omitted [1-9]\d* MCP tool/u);
+});
+
+test('chunks and degrades a dynamic capability group deterministically', () => {
+  const mcpTools = Array.from({ length: 70 }, (_, index) =>
+    tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => 'ok'),
+  );
+  const create = () =>
+    createDesktopNativeCapabilityProvider({
+      browserTools: [],
+      resolveBrowserUrl: () => 'https://example.com/',
+      releaseBrowserSession() {},
+      computerUseTools: [] as never,
+      releaseComputerUseSession() {},
+      additionalGroups: () => [
+        {
+          offerId: 'desktop_mcp',
+          label: 'MCP',
+          description: 'MCP tools connected by this Desktop client.',
+          tools: mcpTools,
+          omitUnsupportedTools: true,
+        },
+      ],
+    });
+  const first = create();
+  const second = create();
+  assert.deepEqual(first.offers(), second.offers());
+});
+
+test('fails loudly when a fixed capability group exceeds the manifest budget', () => {
+  assert.throws(
+    () =>
+      createDesktopNativeCapabilityProvider({
+        browserTools: Array.from({ length: 65 }, (_, index) =>
+          tool(`browser_tool_${index}`, z.object({}), async () => 'ok'),
+        ),
+        resolveBrowserUrl: () => 'https://example.com/',
+        releaseBrowserSession() {},
+        computerUseTools: [] as never,
+        releaseComputerUseSession() {},
+      }),
+    /Invalid Client Capability offer tools/u,
+  );
+});
+
 test('reports provider retirement once after its registration is released', async () => {
   let retirements = 0;
   const provider = createDesktopNativeCapabilityProvider(
diff --git a/apps/desktop/src/main/runtime-host-desktop-candidate.ts b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
index 582e6e9fae..22e0ddfa9b 100644
--- a/apps/desktop/src/main/runtime-host-desktop-candidate.ts
+++ b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
@@ -739,6 +739,7 @@ export async function createDesktopRuntimeHostCandidate(
           onComputerUseTurnUsed: watchComputerUseTurn,
           isTargetValid: deps.isTargetValid,
           onClosed: () => providers.delete(provider),
+          onDiagnostic: logLocalRuntimeHostProcessDiagnostic,
         },
       );
       providers.add(provider);
diff --git a/apps/desktop/src/main/runtime-host-native-capabilities.ts b/apps/desktop/src/main/runtime-host-native-capabilities.ts
index cefcaf7974..c6705f3dc2 100644
--- a/apps/desktop/src/main/runtime-host-native-capabilities.ts
+++ b/apps/desktop/src/main/runtime-host-native-capabilities.ts
@@ -26,6 +26,11 @@ import {
   type OAuthPresentationBackend,
 } from "@maka/runtime-host/client";
 import {
+  CLIENT_CAPABILITY_MAX_MANIFEST_BYTES,
+  CLIENT_CAPABILITY_MAX_OFFERS,
+  CLIENT_CAPABILITY_MAX_TOOLS,
+  CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER,
+  decodeClientCapabilityReplaceInput,
   decodeClientCapabilityToolDescriptor,
   type ClientCapabilityCallFrame,
   type ClientCapabilityCallResult,
@@ -43,6 +48,8 @@ import type { DesktopTargetScope } from '../shared/runtime-host-identity.js';
 const CAPABILITY_VERSION = "0";
 const BROWSER_OFFER_ID = "desktop_browser";
 const COMPUTER_USE_OFFER_ID = "desktop_computer_use";
+// Same wire length as the registrationId the Client Capability channel assigns.
+const MANIFEST_REGISTRATION_ID_PLACEHOLDER = "00000000-0000-4000-8000-000000000000";
 
 export interface DesktopCapabilityGroup {
   readonly offerId: string;
@@ -63,6 +70,7 @@ interface PreparedDesktopCapabilityGroup {
   readonly label: string;
   readonly description: string;
   readonly tools: readonly PreparedDesktopCapabilityTool[];
+  readonly omitUnsupportedTools?: boolean;
 }
 
 type NativeToolBinding = Pick<PreparedDesktopCapabilityTool, "tool">;
@@ -117,6 +125,8 @@ interface DesktopNativeCapabilityProviderOptions {
   readonly onSessionUsed?: (sessionId: string) => void;
   readonly onComputerUseTurnUsed?: (sessionId: string, turnId: string) => void;
   readonly onClosed?: () => void;
+  /** Reports a visible degradation while assembling the published manifest. */
+  readonly onDiagnostic?: (diagnostic: string) => void;
   readonly nativeSessionId?: (sessionId: string) => string;
   readonly targetScope?: DesktopTargetScope;
 }
@@ -127,11 +137,6 @@ export function createDesktopNativeCapabilityProvider(
   providerOptions: DesktopNativeCapabilityProviderOptions = {},
 ): DesktopNativeCapabilityProvider {
   const hostPathAccess = providerOptions.hostPathAccess ?? "cwd";
-  const groups = prepareCapabilityGroups(capabilityGroups(input));
-  const offers = Object.freeze(
-    groups.map((group) => capabilityOffer(group, hostPathAccess)),
-  );
-  const bindings = indexBindings(groups);
   const oauthPresentation = input.oauthPresentation
     ? createOAuthPresentationClientProvider(input.oauthPresentation)
     : undefined;
@@ -139,6 +144,31 @@ export function createDesktopNativeCapabilityProvider(
     ? input.additionalServices(requireTargetScope(providerOptions.targetScope))
     : [];
   const services = indexServices(oauthPresentation?.services?.() ?? [], additionalServices);
+  const serviceOffers = Object.freeze(
+    [...services.values()].map(({ serviceId, version }) =>
+      Object.freeze({ serviceId, version }),
+    ),
+  );
+  const groups = fitDesktopCapabilityManifest(
+    prepareCapabilityGroups(capabilityGroups(input)),
+    serviceOffers,
+    hostPathAccess,
+    providerOptions.onDiagnostic,
+  );
+  const offers = Object.freeze(
+    groups.map((group) => capabilityOffer(group, hostPathAccess)),
+  );
+  // Authoritative check: a manifest that will be sent must decode first, so a
+  // budget overrun can never fail the whole registration at the channel. An
+  // empty provider is legal and never registers.
+  if (offers.length > 0 || serviceOffers.length > 0) {
+    decodeClientCapabilityReplaceInput({
+      registrationId: MANIFEST_REGISTRATION_ID_PLACEHOLDER,
+      offers,
+      ...(serviceOffers.length === 0 ? {} : { services: serviceOffers }),
+    });
+  }
+  const bindings = indexBindings(groups);
   const releaseSessionResources = [
     input.releaseBrowserSession,
     input.releaseComputerUseSession,
@@ -165,7 +195,7 @@ export function createDesktopNativeCapabilityProvider(
 
   return {
     offers: () => offers,
-    services: () => [...services.values()].map(({ serviceId, version }) => ({ serviceId, version })),
+    services: () => [...serviceOffers],
     call: (frame, options) => {
       if (closed)
         throw new Error("Desktop native capability provider is closed");
@@ -469,10 +499,108 @@ function prepareCapabilityGroups(
       return [{ tool, descriptor }];
     });
     if (group.omitUnsupportedTools && tools.length === 0) return [];
-    return [{ ...group, tools }];
+    return chunkPreparedGroup({ ...group, tools });
   });
 }
 
+/**
+ * Split a dynamic group beyond the single-offer tool limit into stable chunks.
+ * Chunked offers keep the group's server identity, so published tool names,
+ * Session Grant scopes, and Host admission never depend on how the group was
+ * split.
+ */
+function chunkPreparedGroup(
+  group: PreparedDesktopCapabilityGroup,
+): PreparedDesktopCapabilityGroup[] {
+  if (
+    !group.omitUnsupportedTools ||
+    group.tools.length <= CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER
+  ) {
+    return [group];
+  }
+  const chunks: PreparedDesktopCapabilityGroup[] = [];
+  for (
+    let offset = 0;
+    offset < group.tools.length;
+    offset += CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER
+  ) {
+    chunks.push({
+      ...group,
+      offerId:
+        offset === 0
+          ? group.offerId
+          : `${group.offerId}_${offset / CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER + 1}`,
+      tools: group.tools.slice(offset, offset + CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER),
+    });
+  }
+  return chunks;
+}
+
+/**
+ * Fit the assembled manifest to the Client Capability budgets before it is
+ * sent. Fixed capability groups are never degraded: if they alone exceed a
+ * budget the registration must fail loudly. Dynamic (omittable) groups shed
+ * their trailing tools instead, and the omission is reported.
+ */
+function fitDesktopCapabilityManifest(
+  groups: readonly PreparedDesktopCapabilityGroup[],
+  services: readonly ClientCapabilityServiceOffer[],
+  hostPathAccess: ClientCapabilityHostPathAccess,
+  onDiagnostic?: (diagnostic: string) => void,
+): PreparedDesktopCapabilityGroup[] {
+  const fitting = groups.map((group) => ({ group, tools: [...group.tools] }));
+  const omitted: string[] = [];
+  const assemble = (): PreparedDesktopCapabilityGroup[] =>
+    fitting
+      .filter((entry) => entry.tools.length > 0)
+      .map((entry) => ({ ...entry.group, tools: entry.tools }));
+  while (!manifestFitsBudget(assemble(), services, hostPathAccess)) {
+    let index = fitting.length - 1;
+    while (
+      index >= 0 &&
+      (!fitting[index]?.group.omitUnsupportedTools || fitting[index]?.tools.length === 0)
+    ) {
+      index -= 1;
+    }
+    const entry = fitting[index];
+    if (!entry) {
+      throw new Error(
+        "Desktop fixed capability groups exceed the Client Capability manifest budget",
+      );
+    }
+    const dropped = entry.tools.pop();
+    if (dropped) omitted.push(dropped.descriptor.name);
+  }
+  if (omitted.length > 0) {
+    const names = omitted.reverse();
+    const shown = names.slice(0, 8).join(", ");
+    onDiagnostic?.(
+      `Desktop omitted ${names.length} MCP tool(s) beyond the Client Capability manifest budget: ${shown}${names.length > 8 ? `, +${names.length - 8} more` : ""}`,
+    );
+  }
+  return assemble();
+}
+
+function manifestFitsBudget(
+  groups: readonly PreparedDesktopCapabilityGroup[],
+  services: readonly ClientCapabilityServiceOffer[],
+  hostPathAccess: ClientCapabilityHostPathAccess,
+): boolean {
+  if (groups.length > CLIENT_CAPABILITY_MAX_OFFERS) return false;
+  const offers = groups.map((group) => capabilityOffer(group, hostPathAccess));
+  let toolCount = 0;
+  for (const offer of offers) toolCount += offer.tools.length;
+  if (toolCount > CLIENT_CAPABILITY_MAX_TOOLS) return false;
+  const manifest = {
+    registrationId: MANIFEST_REGISTRATION_ID_PLACEHOLDER,
+    offers,
+    ...(services.length === 0 ? {} : { services }),
+  };
+  return (
+    Buffer.byteLength(JSON.stringify(manifest), "utf8") <= CLIENT_CAPABILITY_MAX_MANIFEST_BYTES
+  );
+}
+
 function capabilityToolDescriptor(
   offerId: string,
   tool: MakaTool,
@@ -547,11 +675,11 @@ function indexBindings(
 ): Map<string, NativeToolBinding> {
   const bindings = new Map<string, NativeToolBinding>();
   for (const group of groups) {
-    for (const { tool } of group.tools) {
+    for (const { tool, descriptor } of group.tools) {
       const key = bindingKey({
         offerId: group.offerId,
-        serverId: group.offerId,
-        toolName: tool.name,
+        serverId: descriptor.serverId,
+        toolName: descriptor.name,
       });
       if (bindings.has(key)) {
         throw new Error(


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org